blob: e1db2bc24f9426dfa38f79527bb2d27b9a5e7e64 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
Ali Tofigh7fa90572022-03-17 15:47:49 +010013#include "absl/strings/string_view.h"
14
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015#if defined(WEBRTC_WIN)
16#include <comdef.h>
17#elif defined(WEBRTC_POSIX)
18#include <time.h>
Tommi51492422017-12-04 15:18:23 +010019#else
20#error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#endif
22
Artem Titov80d02ad2018-05-21 12:20:39 +020023#if defined(WEBRTC_WIN)
24// Disable warning that we don't care about:
25// warning C4722: destructor never returns, potential memory leak
26#pragma warning(disable : 4722)
27#endif
28
Yves Gerey988cc082018-10-23 12:03:01 +020029#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020030
Yves Gerey988cc082018-10-23 12:03:01 +020031#include <utility>
Yves Gerey2e00abc2018-10-05 15:39:24 +020032
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010033#include "absl/algorithm/container.h"
Artem Titovd15a5752021-02-10 14:31:24 +010034#include "api/sequence_checker.h"
Artem Titovc374d112022-06-16 21:27:45 +020035#include "api/task_queue/to_queued_task.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020037#include "rtc_base/deprecated/recursive_critical_section.h"
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +020038#include "rtc_base/event.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010039#include "rtc_base/internal/default_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/null_socket_server.h"
42#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020045#if defined(WEBRTC_MAC)
46#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020047
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020048/*
49 * These are forward-declarations for methods that are part of the
50 * ObjC runtime. They are declared in the private header objc-internal.h.
51 * These calls are what clang inserts when using @autoreleasepool in ObjC,
52 * but here they are used directly in order to keep this file C++.
53 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
54 */
55extern "C" {
56void* objc_autoreleasePoolPush(void);
57void objc_autoreleasePoolPop(void* pool);
58}
59
60namespace {
61class ScopedAutoReleasePool {
62 public:
63 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
64 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
65
66 private:
67 void* const pool_;
68};
69} // namespace
70#endif
71
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080073namespace {
74
75class MessageHandlerWithTask final : public MessageHandler {
76 public:
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +020077 MessageHandlerWithTask() {}
Steve Antonbcc1a762019-12-11 11:21:53 -080078
Byoungchan Lee14af7622022-01-12 05:24:58 +090079 MessageHandlerWithTask(const MessageHandlerWithTask&) = delete;
80 MessageHandlerWithTask& operator=(const MessageHandlerWithTask&) = delete;
81
Steve Antonbcc1a762019-12-11 11:21:53 -080082 void OnMessage(Message* msg) override {
83 static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
84 delete msg->pdata;
85 }
86
87 private:
88 ~MessageHandlerWithTask() override {}
Steve Antonbcc1a762019-12-11 11:21:53 -080089};
90
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010091class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
92 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020093 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
94 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010095 : cs_(cs), processing_(processing) {
96 cs_->Enter();
97 *processing_ += 1;
98 }
99
100 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
101 *processing_ -= 1;
102 cs_->Leave();
103 }
104
Byoungchan Lee14af7622022-01-12 05:24:58 +0900105 MarkProcessingCritScope(const MarkProcessingCritScope&) = delete;
106 MarkProcessingCritScope& operator=(const MarkProcessingCritScope&) = delete;
107
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100108 private:
Markus Handell3cb525b2020-07-16 16:16:09 +0200109 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100110 size_t* processing_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100111};
112
Steve Antonbcc1a762019-12-11 11:21:53 -0800113} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000114
115ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200116 static ThreadManager* const thread_manager = new ThreadManager();
117 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118}
119
nisse7866cfe2017-04-26 01:45:31 -0700120ThreadManager::~ThreadManager() {
121 // By above RTC_DEFINE_STATIC_LOCAL.
Artem Titovd3251962021-11-15 16:57:07 +0100122 RTC_DCHECK_NOTREACHED() << "ThreadManager should never be destructed.";
nisse7866cfe2017-04-26 01:45:31 -0700123}
124
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100126void ThreadManager::Add(Thread* message_queue) {
127 return Instance()->AddInternal(message_queue);
128}
129void ThreadManager::AddInternal(Thread* message_queue) {
130 CritScope cs(&crit_);
131 // Prevent changes while the list of message queues is processed.
132 RTC_DCHECK_EQ(processing_, 0);
133 message_queues_.push_back(message_queue);
134}
135
136// static
137void ThreadManager::Remove(Thread* message_queue) {
138 return Instance()->RemoveInternal(message_queue);
139}
140void ThreadManager::RemoveInternal(Thread* message_queue) {
141 {
142 CritScope cs(&crit_);
143 // Prevent changes while the list of message queues is processed.
144 RTC_DCHECK_EQ(processing_, 0);
145 std::vector<Thread*>::iterator iter;
146 iter = absl::c_find(message_queues_, message_queue);
147 if (iter != message_queues_.end()) {
148 message_queues_.erase(iter);
149 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100150#if RTC_DCHECK_IS_ON
151 RemoveFromSendGraph(message_queue);
152#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100153 }
154}
155
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100156#if RTC_DCHECK_IS_ON
157void ThreadManager::RemoveFromSendGraph(Thread* thread) {
158 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
159 if (it->first == thread) {
160 it = send_graph_.erase(it);
161 } else {
162 it->second.erase(thread);
163 ++it;
164 }
165 }
166}
167
168void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
169 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200170 RTC_DCHECK(source);
171 RTC_DCHECK(target);
172
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100173 CritScope cs(&crit_);
174 std::deque<Thread*> all_targets({target});
175 // We check the pre-existing who-sends-to-who graph for any path from target
176 // to source. This loop is guaranteed to terminate because per the send graph
177 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800178 for (size_t i = 0; i < all_targets.size(); i++) {
179 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100180 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
181 }
182 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
183 << " send loop between " << source->name() << " and " << target->name();
184
185 // We may now insert source -> target without creating a cycle, since there
186 // was no path from target to source per the prior CHECK.
187 send_graph_[source].insert(target);
188}
189#endif
190
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100191// static
192void ThreadManager::Clear(MessageHandler* handler) {
193 return Instance()->ClearInternal(handler);
194}
195void ThreadManager::ClearInternal(MessageHandler* handler) {
196 // Deleted objects may cause re-entrant calls to ClearInternal. This is
197 // allowed as the list of message queues does not change while queues are
198 // cleared.
199 MarkProcessingCritScope cs(&crit_, &processing_);
200 for (Thread* queue : message_queues_) {
201 queue->Clear(handler);
202 }
203}
204
205// static
206void ThreadManager::ProcessAllMessageQueuesForTesting() {
207 return Instance()->ProcessAllMessageQueuesInternal();
208}
209
210void ThreadManager::ProcessAllMessageQueuesInternal() {
211 // This works by posting a delayed message at the current time and waiting
212 // for it to be dispatched on all queues, which will ensure that all messages
213 // that came before it were also dispatched.
Niels Möller7a669002022-06-27 09:47:02 +0200214 std::atomic<int> queues_not_done(0);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100215
216 // This class is used so that whether the posted message is processed, or the
217 // message queue is simply cleared, queues_not_done gets decremented.
218 class ScopedIncrement : public MessageData {
219 public:
Niels Möller7a669002022-06-27 09:47:02 +0200220 ScopedIncrement(std::atomic<int>* value) : value_(value) {
221 value_->fetch_add(1);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100222 }
Niels Möller7a669002022-06-27 09:47:02 +0200223 ~ScopedIncrement() override { value_->fetch_sub(1); }
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100224
225 private:
Niels Möller7a669002022-06-27 09:47:02 +0200226 std::atomic<int>* value_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100227 };
228
229 {
230 MarkProcessingCritScope cs(&crit_, &processing_);
231 for (Thread* queue : message_queues_) {
232 if (!queue->IsProcessingMessagesForTesting()) {
233 // If the queue is not processing messages, it can
234 // be ignored. If we tried to post a message to it, it would be dropped
235 // or ignored.
236 continue;
237 }
238 queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
239 new ScopedIncrement(&queues_not_done));
240 }
241 }
242
243 rtc::Thread* current = rtc::Thread::Current();
244 // Note: One of the message queues may have been on this thread, which is
245 // why we can't synchronously wait for queues_not_done to go to 0; we need
246 // to process messages as well.
Niels Möller7a669002022-06-27 09:47:02 +0200247 while (queues_not_done.load() > 0) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100248 if (current) {
249 current->ProcessMessages(0);
250 }
251 }
252}
253
254// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700256 ThreadManager* manager = ThreadManager::Instance();
257 Thread* thread = manager->CurrentThread();
258
nisse7866cfe2017-04-26 01:45:31 -0700259 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260}
261
262#if defined(WEBRTC_POSIX)
Niels Möller98d26df2022-02-07 10:35:29 +0100263ThreadManager::ThreadManager() {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200264#if defined(WEBRTC_MAC)
265 InitCocoaMultiThreading();
266#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800267 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000268}
269
Yves Gerey665174f2018-06-19 15:03:05 +0200270Thread* ThreadManager::CurrentThread() {
271 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272}
273
Sebastian Jansson178a6852020-01-14 11:12:26 +0100274void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275 pthread_setspecific(key_, thread);
276}
277#endif
278
279#if defined(WEBRTC_WIN)
Niels Möller98d26df2022-02-07 10:35:29 +0100280ThreadManager::ThreadManager() : key_(TlsAlloc()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200281
282Thread* ThreadManager::CurrentThread() {
283 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000284}
285
Sebastian Jansson178a6852020-01-14 11:12:26 +0100286void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287 TlsSetValue(key_, thread);
288}
289#endif
290
Sebastian Jansson178a6852020-01-14 11:12:26 +0100291void ThreadManager::SetCurrentThread(Thread* thread) {
292#if RTC_DLOG_IS_ON
293 if (CurrentThread() && thread) {
294 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
295 }
296#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200297
298 if (thread) {
299 thread->EnsureIsCurrentTaskQueue();
300 } else {
301 Thread* current = CurrentThread();
302 if (current) {
303 // The current thread is being cleared, e.g. as a result of
304 // UnwrapCurrent() being called or when a thread is being stopped
305 // (see PreRun()). This signals that the Thread instance is being detached
306 // from the thread, which also means that TaskQueue::Current() must not
307 // return a pointer to the Thread instance.
308 current->ClearCurrentTaskQueue();
309 }
310 }
311
Sebastian Jansson178a6852020-01-14 11:12:26 +0100312 SetCurrentThreadInternal(thread);
313}
314
315void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
316 SetCurrentThreadInternal(thread);
317}
318
Yves Gerey665174f2018-06-19 15:03:05 +0200319Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800321 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100322 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000323 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324 }
325 return result;
326}
327
328void ThreadManager::UnwrapCurrentThread() {
329 Thread* t = CurrentThread();
330 if (t && !(t->IsOwned())) {
331 t->UnwrapCurrent();
332 delete t;
333 }
334}
335
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000336Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200337 : thread_(Thread::Current()),
338 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000339
340Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800341 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000342 thread_->SetAllowBlockingCalls(previous_state_);
343}
344
Tommife041642021-04-07 10:08:28 +0200345#if RTC_DCHECK_IS_ON
346Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls(
347 std::function<void(uint32_t, uint32_t)> callback)
348 : thread_(Thread::Current()),
349 base_blocking_call_count_(thread_->GetBlockingCallCount()),
350 base_could_be_blocking_call_count_(
351 thread_->GetCouldBeBlockingCallCount()),
352 result_callback_(std::move(callback)) {}
353
354Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() {
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200355 if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) {
356 result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount());
357 }
Tommife041642021-04-07 10:08:28 +0200358}
359
360uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const {
361 return thread_->GetBlockingCallCount() - base_blocking_call_count_;
362}
363
364uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const {
365 return thread_->GetCouldBeBlockingCallCount() -
366 base_could_be_blocking_call_count_;
367}
368
369uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const {
370 return GetBlockingCallCount() + GetCouldBeBlockingCallCount();
371}
372#endif
373
Taylor Brandstetter08672602018-03-02 15:20:33 -0800374Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700375
376Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800377 : Thread(std::move(ss), /*do_init=*/true) {}
378
379Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100380 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100381 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100382 fInitialized_(false),
383 fDestroyed_(false),
384 stop_(0),
385 ss_(ss) {
386 RTC_DCHECK(ss);
387 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800388 SetName("Thread", this); // default name
389 if (do_init) {
390 DoInit();
391 }
392}
393
394Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100395 : Thread(ss.get(), do_init) {
396 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000397}
398
399Thread::~Thread() {
400 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800401 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000402}
403
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100404void Thread::DoInit() {
405 if (fInitialized_) {
406 return;
407 }
408
409 fInitialized_ = true;
410 ThreadManager::Add(this);
411}
412
413void Thread::DoDestroy() {
414 if (fDestroyed_) {
415 return;
416 }
417
418 fDestroyed_ = true;
419 // The signal is done from here to ensure
420 // that it always gets called when the queue
421 // is going away.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100422 if (ss_) {
423 ss_->SetMessageQueue(nullptr);
424 }
Niels Möller9bd24572021-04-19 12:18:27 +0200425 ThreadManager::Remove(this);
426 ClearInternal(nullptr, MQID_ANY, nullptr);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100427}
428
429SocketServer* Thread::socketserver() {
430 return ss_;
431}
432
433void Thread::WakeUpSocketServer() {
434 ss_->WakeUp();
435}
436
437void Thread::Quit() {
Niels Möller7a669002022-06-27 09:47:02 +0200438 stop_.store(1, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100439 WakeUpSocketServer();
440}
441
442bool Thread::IsQuitting() {
Niels Möller7a669002022-06-27 09:47:02 +0200443 return stop_.load(std::memory_order_acquire) != 0;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100444}
445
446void Thread::Restart() {
Niels Möller7a669002022-06-27 09:47:02 +0200447 stop_.store(0, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100448}
449
450bool Thread::Peek(Message* pmsg, int cmsWait) {
451 if (fPeekKeep_) {
452 *pmsg = msgPeek_;
453 return true;
454 }
455 if (!Get(pmsg, cmsWait))
456 return false;
457 msgPeek_ = *pmsg;
458 fPeekKeep_ = true;
459 return true;
460}
461
462bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
463 // Return and clear peek if present
464 // Always return the peek if it exists so there is Peek/Get symmetry
465
466 if (fPeekKeep_) {
467 *pmsg = msgPeek_;
468 fPeekKeep_ = false;
469 return true;
470 }
471
472 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
473
474 int64_t cmsTotal = cmsWait;
475 int64_t cmsElapsed = 0;
476 int64_t msStart = TimeMillis();
477 int64_t msCurrent = msStart;
478 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100479 // Check for posted events
480 int64_t cmsDelayNext = kForever;
481 bool first_pass = true;
482 while (true) {
483 // All queue operations need to be locked, but nothing else in this loop
484 // (specifically handling disposed message) can happen inside the crit.
485 // Otherwise, disposed MessageHandlers will cause deadlocks.
486 {
487 CritScope cs(&crit_);
488 // On the first pass, check for delayed messages that have been
489 // triggered and calculate the next trigger time.
490 if (first_pass) {
491 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100492 while (!delayed_messages_.empty()) {
493 if (msCurrent < delayed_messages_.top().run_time_ms_) {
494 cmsDelayNext =
495 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100496 break;
497 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100498 messages_.push_back(delayed_messages_.top().msg_);
499 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100500 }
501 }
502 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100503 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100504 break;
505 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100506 *pmsg = messages_.front();
507 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100508 }
509 } // crit_ is released here.
510
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100511 // If this was a dispose message, delete it and skip it.
512 if (MQID_DISPOSE == pmsg->message_id) {
513 RTC_DCHECK(nullptr == pmsg->phandler);
514 delete pmsg->pdata;
515 *pmsg = Message();
516 continue;
517 }
518 return true;
519 }
520
521 if (IsQuitting())
522 break;
523
524 // Which is shorter, the delay wait or the asked wait?
525
526 int64_t cmsNext;
527 if (cmsWait == kForever) {
528 cmsNext = cmsDelayNext;
529 } else {
530 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
531 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
532 cmsNext = cmsDelayNext;
533 }
534
535 {
536 // Wait and multiplex in the meantime
537 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
538 return false;
539 }
540
541 // If the specified timeout expired, return
542
543 msCurrent = TimeMillis();
544 cmsElapsed = TimeDiff(msCurrent, msStart);
545 if (cmsWait != kForever) {
546 if (cmsElapsed >= cmsWait)
547 return false;
548 }
549 }
550 return false;
551}
552
553void Thread::Post(const Location& posted_from,
554 MessageHandler* phandler,
555 uint32_t id,
556 MessageData* pdata,
557 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100558 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100559 if (IsQuitting()) {
560 delete pdata;
561 return;
562 }
563
564 // Keep thread safe
565 // Add the message to the end of the queue
566 // Signal for the multiplexer to return
567
568 {
569 CritScope cs(&crit_);
570 Message msg;
571 msg.posted_from = posted_from;
572 msg.phandler = phandler;
573 msg.message_id = id;
574 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100575 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100576 }
577 WakeUpSocketServer();
578}
579
580void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100581 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100582 MessageHandler* phandler,
583 uint32_t id,
584 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100585 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100586 pdata);
587}
588
589void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100590 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100591 MessageHandler* phandler,
592 uint32_t id,
593 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100594 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100595 pdata);
596}
597
598void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100599 int64_t delay_ms,
600 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100601 MessageHandler* phandler,
602 uint32_t id,
603 MessageData* pdata) {
604 if (IsQuitting()) {
605 delete pdata;
606 return;
607 }
608
609 // Keep thread safe
610 // Add to the priority queue. Gets sorted soonest first.
611 // Signal for the multiplexer to return.
612
613 {
614 CritScope cs(&crit_);
615 Message msg;
616 msg.posted_from = posted_from;
617 msg.phandler = phandler;
618 msg.message_id = id;
619 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100620 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
621 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100622 // If this message queue processes 1 message every millisecond for 50 days,
623 // we will wrap this number. Even then, only messages with identical times
624 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100625 ++delayed_next_num_;
626 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100627 }
628 WakeUpSocketServer();
629}
630
631int Thread::GetDelay() {
632 CritScope cs(&crit_);
633
Sebastian Jansson61380c02020-01-17 14:46:08 +0100634 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100635 return 0;
636
Sebastian Jansson61380c02020-01-17 14:46:08 +0100637 if (!delayed_messages_.empty()) {
638 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100639 if (delay < 0)
640 delay = 0;
641 return delay;
642 }
643
644 return kForever;
645}
646
647void Thread::ClearInternal(MessageHandler* phandler,
648 uint32_t id,
649 MessageList* removed) {
650 // Remove messages with phandler
651
652 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
653 if (removed) {
654 removed->push_back(msgPeek_);
655 } else {
656 delete msgPeek_.pdata;
657 }
658 fPeekKeep_ = false;
659 }
660
661 // Remove from ordered message queue
662
Sebastian Jansson61380c02020-01-17 14:46:08 +0100663 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100664 if (it->Match(phandler, id)) {
665 if (removed) {
666 removed->push_back(*it);
667 } else {
668 delete it->pdata;
669 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100670 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100671 } else {
672 ++it;
673 }
674 }
675
676 // Remove from priority queue. Not directly iterable, so use this approach
677
Sebastian Jansson61380c02020-01-17 14:46:08 +0100678 auto new_end = delayed_messages_.container().begin();
679 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100680 if (it->msg_.Match(phandler, id)) {
681 if (removed) {
682 removed->push_back(it->msg_);
683 } else {
684 delete it->msg_.pdata;
685 }
686 } else {
687 *new_end++ = *it;
688 }
689 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100690 delayed_messages_.container().erase(new_end,
691 delayed_messages_.container().end());
692 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100693}
694
695void Thread::Dispatch(Message* pmsg) {
696 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
697 pmsg->posted_from.file_name(), "src_func",
698 pmsg->posted_from.function_name());
Harald Alvestrandba694422021-01-27 21:52:14 +0000699 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100700 int64_t start_time = TimeMillis();
701 pmsg->phandler->OnMessage(pmsg);
702 int64_t end_time = TimeMillis();
703 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000704 if (diff >= dispatch_warning_ms_) {
705 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100706 << "ms to dispatch. Posted from: "
707 << pmsg->posted_from.ToString();
Harald Alvestrandba694422021-01-27 21:52:14 +0000708 // To avoid log spew, move the warning limit to only give warning
709 // for delays that are larger than the one observed.
710 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100711 }
712}
713
nisse7866cfe2017-04-26 01:45:31 -0700714bool Thread::IsCurrent() const {
715 return ThreadManager::Instance()->CurrentThread() == this;
716}
717
danilchapbebf54c2016-04-28 01:32:48 -0700718std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100719 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700720}
721
722std::unique_ptr<Thread> Thread::Create() {
723 return std::unique_ptr<Thread>(
724 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
725}
726
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000727bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000728 AssertBlockingIsAllowedOnCurrentThread();
729
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000730#if defined(WEBRTC_WIN)
731 ::Sleep(milliseconds);
732 return true;
733#else
734 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
735 // so we use nanosleep() even though it has greater precision than necessary.
736 struct timespec ts;
737 ts.tv_sec = milliseconds / 1000;
738 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800739 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000740 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100741 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000742 return false;
743 }
744 return true;
745#endif
746}
747
Ali Tofigh7fa90572022-03-17 15:47:49 +0100748bool Thread::SetName(absl::string_view name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100749 RTC_DCHECK(!IsRunning());
750
Ali Tofigh7fa90572022-03-17 15:47:49 +0100751 name_ = std::string(name);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000752 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200753 // The %p specifier typically produce at most 16 hex digits, possibly with a
754 // 0x prefix. But format is implementation defined, so add some margin.
755 char buf[30];
756 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000757 name_ += buf;
758 }
759 return true;
760}
761
Harald Alvestrandba694422021-01-27 21:52:14 +0000762void Thread::SetDispatchWarningMs(int deadline) {
763 if (!IsCurrent()) {
764 PostTask(webrtc::ToQueuedTask(
765 [this, deadline]() { SetDispatchWarningMs(deadline); }));
766 return;
767 }
768 RTC_DCHECK_RUN_ON(this);
769 dispatch_warning_ms_ = deadline;
770}
771
Niels Möllerd2e50132019-06-11 09:24:14 +0200772bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100773 RTC_DCHECK(!IsRunning());
774
775 if (IsRunning())
776 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000777
André Susano Pinto02a57972016-07-22 13:30:05 +0200778 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000779
780 // Make sure that ThreadManager is created on the main thread before
781 // we start a new thread.
782 ThreadManager::Instance();
783
Tommi51492422017-12-04 15:18:23 +0100784 owned_ = true;
785
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000786#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200787 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100788 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000789 return false;
790 }
791#elif defined(WEBRTC_POSIX)
792 pthread_attr_t attr;
793 pthread_attr_init(&attr);
794
Niels Möllerd2e50132019-06-11 09:24:14 +0200795 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000796 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100797 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100798 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000799 return false;
800 }
Tommi51492422017-12-04 15:18:23 +0100801 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000802#endif
803 return true;
804}
805
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000806bool Thread::WrapCurrent() {
807 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
808}
809
810void Thread::UnwrapCurrent() {
811 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800812 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000813#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800814 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000815 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100816 RTC_LOG_GLE(LS_ERROR)
817 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000818 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800819 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100820 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000821 }
Tommi51492422017-12-04 15:18:23 +0100822#elif defined(WEBRTC_POSIX)
823 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000824#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000825}
826
827void Thread::SafeWrapCurrent() {
828 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
829}
830
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000831void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100832 if (!IsRunning())
833 return;
834
835 RTC_DCHECK(!IsCurrent());
836 if (Current() && !Current()->blocking_calls_allowed_) {
837 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100838 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100839 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000840
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000841#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100842 RTC_DCHECK(thread_ != nullptr);
843 WaitForSingleObject(thread_, INFINITE);
844 CloseHandle(thread_);
845 thread_ = nullptr;
846 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000847#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100848 pthread_join(thread_, nullptr);
849 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000850#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000851}
852
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000853bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800854 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000855 bool previous = blocking_calls_allowed_;
856 blocking_calls_allowed_ = allow;
857 return previous;
858}
859
860// static
861void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700862#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000863 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800864 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000865#endif
866}
867
deadbeefdc20e262017-01-31 15:10:44 -0800868// static
869#if defined(WEBRTC_WIN)
870DWORD WINAPI Thread::PreRun(LPVOID pv) {
871#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000872void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800873#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200874 Thread* thread = static_cast<Thread*>(pv);
875 ThreadManager::Instance()->SetCurrentThread(thread);
876 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200877#if defined(WEBRTC_MAC)
878 ScopedAutoReleasePool pool;
879#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200880 thread->Run();
881
Tommi51492422017-12-04 15:18:23 +0100882 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800883#ifdef WEBRTC_WIN
884 return 0;
885#else
886 return nullptr;
887#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200888} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000889
890void Thread::Run() {
891 ProcessMessages(kForever);
892}
893
894bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100895 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000896 return owned_;
897}
898
899void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100900 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000901 Join();
902}
903
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700904void Thread::Send(const Location& posted_from,
905 MessageHandler* phandler,
906 uint32_t id,
907 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100908 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200909 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000910 return;
911
912 // Sent messages are sent to the MessageHandler directly, in the context
913 // of "thread", like Win32 SendMessage. If in the right context,
914 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000915 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700916 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000917 msg.phandler = phandler;
918 msg.message_id = id;
919 msg.pdata = pdata;
920 if (IsCurrent()) {
Tommife041642021-04-07 10:08:28 +0200921#if RTC_DCHECK_IS_ON
Artem Titov15737162021-05-25 11:17:07 +0200922 RTC_DCHECK(this->IsInvokeToThreadAllowed(this));
Tommife041642021-04-07 10:08:28 +0200923 RTC_DCHECK_RUN_ON(this);
924 could_be_blocking_call_count_++;
925#endif
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100926 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000927 return;
928 }
929
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000930 AssertBlockingIsAllowedOnCurrentThread();
931
Yves Gerey665174f2018-06-19 15:03:05 +0200932 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200933
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100934#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200935 if (current_thread) {
Tommife041642021-04-07 10:08:28 +0200936 RTC_DCHECK_RUN_ON(current_thread);
937 current_thread->blocking_call_count_++;
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200938 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
939 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
940 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000941 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200942#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000943
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200944 // Perhaps down the line we can get rid of this workaround and always require
945 // current_thread to be valid when Send() is called.
946 std::unique_ptr<rtc::Event> done_event;
947 if (!current_thread)
948 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000949
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200950 bool ready = false;
951 PostTask(webrtc::ToQueuedTask(
952 [&msg]() mutable { msg.phandler->OnMessage(&msg); },
953 [this, &ready, current_thread, done = done_event.get()] {
954 if (current_thread) {
955 CritScope cs(&crit_);
956 ready = true;
957 current_thread->socketserver()->WakeUp();
958 } else {
959 done->Set();
960 }
961 }));
962
963 if (current_thread) {
964 bool waited = false;
965 crit_.Enter();
966 while (!ready) {
967 crit_.Leave();
968 current_thread->socketserver()->Wait(kForever, false);
969 waited = true;
970 crit_.Enter();
971 }
972 crit_.Leave();
973
974 // Our Wait loop above may have consumed some WakeUp events for this
975 // Thread, that weren't relevant to this Send. Losing these WakeUps can
976 // cause problems for some SocketServers.
977 //
978 // Concrete example:
979 // Win32SocketServer on thread A calls Send on thread B. While processing
980 // the message, thread B Posts a message to A. We consume the wakeup for
981 // that Post while waiting for the Send to complete, which means that when
982 // we exit this loop, we need to issue another WakeUp, or else the Posted
983 // message won't be processed in a timely manner.
984
985 if (waited) {
986 current_thread->socketserver()->WakeUp();
987 }
988 } else {
989 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000990 }
991}
992
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700993void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100994 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800995 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
996 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100997
998 class FunctorMessageHandler : public MessageHandler {
999 public:
1000 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +02001001 : functor_(functor) {}
Danil Chapovalov89313452019-11-29 12:56:43 +01001002 void OnMessage(Message* msg) override { functor_(); }
1003
1004 private:
1005 rtc::FunctionView<void()> functor_;
1006 } handler(functor);
1007
1008 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +00001009}
1010
Tommi6866dc72020-05-15 10:11:56 +02001011// Called by the ThreadManager when being set as the current thread.
1012void Thread::EnsureIsCurrentTaskQueue() {
1013 task_queue_registration_ =
1014 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
1015}
1016
1017// Called by the ThreadManager when being set as the current thread.
1018void Thread::ClearCurrentTaskQueue() {
1019 task_queue_registration_.reset();
1020}
1021
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001022void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
1023 RTC_DCHECK(msg);
1024 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
Mirko Bonadei179b46b2021-07-24 21:50:24 +02001025 std::unique_ptr<webrtc::QueuedTask> task(data->Release());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001026 // Thread expects handler to own Message::pdata when OnMessage is called
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001027 // Since MessageData is no longer needed, delete it.
1028 delete data;
1029
1030 // QueuedTask interface uses Run return value to communicate who owns the
1031 // task. false means QueuedTask took the ownership.
1032 if (!task->Run())
1033 task.release();
1034}
1035
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001036void Thread::AllowInvokesToThread(Thread* thread) {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001037#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001038 if (!IsCurrent()) {
1039 PostTask(webrtc::ToQueuedTask(
1040 [thread, this]() { AllowInvokesToThread(thread); }));
1041 return;
1042 }
1043 RTC_DCHECK_RUN_ON(this);
1044 allowed_threads_.push_back(thread);
1045 invoke_policy_enabled_ = true;
1046#endif
1047}
1048
1049void Thread::DisallowAllInvokes() {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001050#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001051 if (!IsCurrent()) {
1052 PostTask(webrtc::ToQueuedTask([this]() { DisallowAllInvokes(); }));
1053 return;
1054 }
1055 RTC_DCHECK_RUN_ON(this);
1056 allowed_threads_.clear();
1057 invoke_policy_enabled_ = true;
1058#endif
1059}
1060
Tommife041642021-04-07 10:08:28 +02001061#if RTC_DCHECK_IS_ON
1062uint32_t Thread::GetBlockingCallCount() const {
1063 RTC_DCHECK_RUN_ON(this);
1064 return blocking_call_count_;
1065}
1066uint32_t Thread::GetCouldBeBlockingCallCount() const {
1067 RTC_DCHECK_RUN_ON(this);
1068 return could_be_blocking_call_count_;
1069}
1070#endif
1071
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001072// Returns true if no policies added or if there is at least one policy
Artem Titov96e3b992021-07-26 16:03:14 +02001073// that permits invocation to `target` thread.
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001074bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001075#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001076 RTC_DCHECK_RUN_ON(this);
1077 if (!invoke_policy_enabled_) {
1078 return true;
1079 }
1080 for (const auto* thread : allowed_threads_) {
1081 if (thread == target) {
1082 return true;
1083 }
1084 }
1085 return false;
1086#else
1087 return true;
1088#endif
1089}
1090
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001091void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
1092 // Though Post takes MessageData by raw pointer (last parameter), it still
1093 // takes it with ownership.
1094 Post(RTC_FROM_HERE, &queued_task_handler_,
1095 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1096}
1097
1098void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
1099 uint32_t milliseconds) {
Henrik Boströmcf9899c2022-01-20 09:46:16 +01001100 // This implementation does not support low precision yet.
1101 PostDelayedHighPrecisionTask(std::move(task), milliseconds);
1102}
1103
1104void Thread::PostDelayedHighPrecisionTask(
1105 std::unique_ptr<webrtc::QueuedTask> task,
1106 uint32_t milliseconds) {
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001107 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1108 // it still takes it with ownership.
Henrik Boströmcf9899c2022-01-20 09:46:16 +01001109 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_, /*id=*/0,
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001110 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1111}
1112
1113void Thread::Delete() {
1114 Stop();
1115 delete this;
1116}
1117
Niels Möller8909a632018-09-06 08:42:44 +02001118bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001119 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001120}
1121
Peter Boström0c4e06b2015-10-07 12:23:21 +02001122void Thread::Clear(MessageHandler* phandler,
1123 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001124 MessageList* removed) {
1125 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001126 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001127}
1128
1129bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001130 // Using ProcessMessages with a custom clock for testing and a time greater
1131 // than 0 doesn't work, since it's not guaranteed to advance the custom
1132 // clock's time, and may get stuck in an infinite loop.
1133 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1134 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001135 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001136 int cmsNext = cmsLoop;
1137
1138 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001139#if defined(WEBRTC_MAC)
1140 ScopedAutoReleasePool pool;
1141#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001142 Message msg;
1143 if (!Get(&msg, cmsNext))
1144 return !IsQuitting();
1145 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001146
kthelgasonde6adbe2017-02-22 00:42:11 -08001147 if (cmsLoop != kForever) {
1148 cmsNext = static_cast<int>(TimeUntil(msEnd));
1149 if (cmsNext < 0)
1150 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001151 }
1152 }
1153}
1154
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001155bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1156 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001157 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001158
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001159#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001160 if (need_synchronize_access) {
1161 // We explicitly ask for no rights other than synchronization.
1162 // This gives us the best chance of succeeding.
1163 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1164 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001165 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001166 return false;
1167 }
1168 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001169 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001170#elif defined(WEBRTC_POSIX)
1171 thread_ = pthread_self();
1172#endif
1173 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001174 thread_manager->SetCurrentThread(this);
1175 return true;
1176}
1177
Tommi51492422017-12-04 15:18:23 +01001178bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001179#if defined(WEBRTC_WIN)
1180 return thread_ != nullptr;
1181#elif defined(WEBRTC_POSIX)
1182 return thread_ != 0;
1183#endif
1184}
1185
Steve Antonbcc1a762019-12-11 11:21:53 -08001186// static
1187MessageHandler* Thread::GetPostTaskMessageHandler() {
1188 // Allocate at first call, never deallocate.
1189 static MessageHandler* handler = new MessageHandlerWithTask;
1190 return handler;
1191}
1192
Taylor Brandstetter08672602018-03-02 15:20:33 -08001193AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +01001194 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001195 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001196 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001197 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1198 // post a message to a queue that no running thread is serving.
1199 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001200 ThreadManager::Instance()->SetCurrentThread(this);
1201 }
1202}
1203
1204AutoThread::~AutoThread() {
1205 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001206 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001207 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001208 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001209 }
1210}
1211
nisse7eaa4ea2017-05-08 05:25:41 -07001212AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001213 : Thread(ss, /*do_init=*/false) {
1214 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001215 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001216 // Temporarily set the current thread to nullptr so that we can keep checks
1217 // around that catch unintentional pointer overwrites.
1218 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001219 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1220 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001221 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001222 }
1223}
1224
1225AutoSocketServerThread::~AutoSocketServerThread() {
1226 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
Steve Anton3b80aac2017-10-19 10:17:12 -07001227 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001228 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001229 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1230 // its contents rely on this thread still being set as the current thread.
1231 Stop();
1232 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001233 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001234 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1235 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001236 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001237 }
1238}
1239
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001240} // namespace rtc