blob: 5a5c142c010c572d2b6d49c44c8a6c41af2edba9 [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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013#if defined(WEBRTC_WIN)
14#include <comdef.h>
15#elif defined(WEBRTC_POSIX)
16#include <time.h>
Tommi51492422017-12-04 15:18:23 +010017#else
18#error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#endif
20
Artem Titov80d02ad2018-05-21 12:20:39 +020021#if defined(WEBRTC_WIN)
22// Disable warning that we don't care about:
23// warning C4722: destructor never returns, potential memory leak
24#pragma warning(disable : 4722)
25#endif
26
Yves Gerey988cc082018-10-23 12:03:01 +020027#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020028
Yves Gerey988cc082018-10-23 12:03:01 +020029#include <utility>
Yves Gerey2e00abc2018-10-05 15:39:24 +020030
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010031#include "absl/algorithm/container.h"
32#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020034#include "rtc_base/deprecated/recursive_critical_section.h"
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +020035#include "rtc_base/event.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010036#include "rtc_base/internal/default_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/null_socket_server.h"
Artem Titovdfc5f0d2020-07-03 12:09:26 +020039#include "rtc_base/synchronization/sequence_checker.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010040#include "rtc_base/task_utils/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020044#if defined(WEBRTC_MAC)
45#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020046
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020047/*
48 * These are forward-declarations for methods that are part of the
49 * ObjC runtime. They are declared in the private header objc-internal.h.
50 * These calls are what clang inserts when using @autoreleasepool in ObjC,
51 * but here they are used directly in order to keep this file C++.
52 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
53 */
54extern "C" {
55void* objc_autoreleasePoolPush(void);
56void objc_autoreleasePoolPop(void* pool);
57}
58
59namespace {
60class ScopedAutoReleasePool {
61 public:
62 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
63 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
64
65 private:
66 void* const pool_;
67};
68} // namespace
69#endif
70
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080072namespace {
73
74class MessageHandlerWithTask final : public MessageHandler {
75 public:
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +020076 MessageHandlerWithTask() {}
Steve Antonbcc1a762019-12-11 11:21:53 -080077
78 void OnMessage(Message* msg) override {
79 static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
80 delete msg->pdata;
81 }
82
83 private:
84 ~MessageHandlerWithTask() override {}
85
86 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
87};
88
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010089class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
90 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020091 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
92 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010093 : cs_(cs), processing_(processing) {
94 cs_->Enter();
95 *processing_ += 1;
96 }
97
98 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
99 *processing_ -= 1;
100 cs_->Leave();
101 }
102
103 private:
Markus Handell3cb525b2020-07-16 16:16:09 +0200104 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100105 size_t* processing_;
106
107 RTC_DISALLOW_COPY_AND_ASSIGN(MarkProcessingCritScope);
108};
109
Steve Antonbcc1a762019-12-11 11:21:53 -0800110} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111
112ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200113 static ThreadManager* const thread_manager = new ThreadManager();
114 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115}
116
nisse7866cfe2017-04-26 01:45:31 -0700117ThreadManager::~ThreadManager() {
118 // By above RTC_DEFINE_STATIC_LOCAL.
119 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
120}
121
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000122// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100123void ThreadManager::Add(Thread* message_queue) {
124 return Instance()->AddInternal(message_queue);
125}
126void ThreadManager::AddInternal(Thread* message_queue) {
127 CritScope cs(&crit_);
128 // Prevent changes while the list of message queues is processed.
129 RTC_DCHECK_EQ(processing_, 0);
130 message_queues_.push_back(message_queue);
131}
132
133// static
134void ThreadManager::Remove(Thread* message_queue) {
135 return Instance()->RemoveInternal(message_queue);
136}
137void ThreadManager::RemoveInternal(Thread* message_queue) {
138 {
139 CritScope cs(&crit_);
140 // Prevent changes while the list of message queues is processed.
141 RTC_DCHECK_EQ(processing_, 0);
142 std::vector<Thread*>::iterator iter;
143 iter = absl::c_find(message_queues_, message_queue);
144 if (iter != message_queues_.end()) {
145 message_queues_.erase(iter);
146 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100147#if RTC_DCHECK_IS_ON
148 RemoveFromSendGraph(message_queue);
149#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100150 }
151}
152
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100153#if RTC_DCHECK_IS_ON
154void ThreadManager::RemoveFromSendGraph(Thread* thread) {
155 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
156 if (it->first == thread) {
157 it = send_graph_.erase(it);
158 } else {
159 it->second.erase(thread);
160 ++it;
161 }
162 }
163}
164
165void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
166 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200167 RTC_DCHECK(source);
168 RTC_DCHECK(target);
169
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100170 CritScope cs(&crit_);
171 std::deque<Thread*> all_targets({target});
172 // We check the pre-existing who-sends-to-who graph for any path from target
173 // to source. This loop is guaranteed to terminate because per the send graph
174 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800175 for (size_t i = 0; i < all_targets.size(); i++) {
176 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100177 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
178 }
179 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
180 << " send loop between " << source->name() << " and " << target->name();
181
182 // We may now insert source -> target without creating a cycle, since there
183 // was no path from target to source per the prior CHECK.
184 send_graph_[source].insert(target);
185}
186#endif
187
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100188// static
189void ThreadManager::Clear(MessageHandler* handler) {
190 return Instance()->ClearInternal(handler);
191}
192void ThreadManager::ClearInternal(MessageHandler* handler) {
193 // Deleted objects may cause re-entrant calls to ClearInternal. This is
194 // allowed as the list of message queues does not change while queues are
195 // cleared.
196 MarkProcessingCritScope cs(&crit_, &processing_);
197 for (Thread* queue : message_queues_) {
198 queue->Clear(handler);
199 }
200}
201
202// static
203void ThreadManager::ProcessAllMessageQueuesForTesting() {
204 return Instance()->ProcessAllMessageQueuesInternal();
205}
206
207void ThreadManager::ProcessAllMessageQueuesInternal() {
208 // This works by posting a delayed message at the current time and waiting
209 // for it to be dispatched on all queues, which will ensure that all messages
210 // that came before it were also dispatched.
211 volatile int queues_not_done = 0;
212
213 // This class is used so that whether the posted message is processed, or the
214 // message queue is simply cleared, queues_not_done gets decremented.
215 class ScopedIncrement : public MessageData {
216 public:
217 ScopedIncrement(volatile int* value) : value_(value) {
218 AtomicOps::Increment(value_);
219 }
220 ~ScopedIncrement() override { AtomicOps::Decrement(value_); }
221
222 private:
223 volatile int* value_;
224 };
225
226 {
227 MarkProcessingCritScope cs(&crit_, &processing_);
228 for (Thread* queue : message_queues_) {
229 if (!queue->IsProcessingMessagesForTesting()) {
230 // If the queue is not processing messages, it can
231 // be ignored. If we tried to post a message to it, it would be dropped
232 // or ignored.
233 continue;
234 }
235 queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
236 new ScopedIncrement(&queues_not_done));
237 }
238 }
239
240 rtc::Thread* current = rtc::Thread::Current();
241 // Note: One of the message queues may have been on this thread, which is
242 // why we can't synchronously wait for queues_not_done to go to 0; we need
243 // to process messages as well.
244 while (AtomicOps::AcquireLoad(&queues_not_done) > 0) {
245 if (current) {
246 current->ProcessMessages(0);
247 }
248 }
249}
250
251// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700253 ThreadManager* manager = ThreadManager::Instance();
254 Thread* thread = manager->CurrentThread();
255
Niels Moller9d1840c2019-05-21 07:26:37 +0000256#ifndef NO_MAIN_THREAD_WRAPPING
257 // Only autowrap the thread which instantiated the ThreadManager.
258 if (!thread && manager->IsMainThread()) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100259 thread = new Thread(CreateDefaultSocketServer());
Niels Moller9d1840c2019-05-21 07:26:37 +0000260 thread->WrapCurrentWithThreadManager(manager, true);
261 }
262#endif
263
nisse7866cfe2017-04-26 01:45:31 -0700264 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265}
266
267#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +0000268ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200269#if defined(WEBRTC_MAC)
270 InitCocoaMultiThreading();
271#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800272 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273}
274
Yves Gerey665174f2018-06-19 15:03:05 +0200275Thread* ThreadManager::CurrentThread() {
276 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277}
278
Sebastian Jansson178a6852020-01-14 11:12:26 +0100279void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000280 pthread_setspecific(key_, thread);
281}
282#endif
283
284#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000285ThreadManager::ThreadManager()
286 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200287
288Thread* ThreadManager::CurrentThread() {
289 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290}
291
Sebastian Jansson178a6852020-01-14 11:12:26 +0100292void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293 TlsSetValue(key_, thread);
294}
295#endif
296
Sebastian Jansson178a6852020-01-14 11:12:26 +0100297void ThreadManager::SetCurrentThread(Thread* thread) {
298#if RTC_DLOG_IS_ON
299 if (CurrentThread() && thread) {
300 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
301 }
302#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200303
304 if (thread) {
305 thread->EnsureIsCurrentTaskQueue();
306 } else {
307 Thread* current = CurrentThread();
308 if (current) {
309 // The current thread is being cleared, e.g. as a result of
310 // UnwrapCurrent() being called or when a thread is being stopped
311 // (see PreRun()). This signals that the Thread instance is being detached
312 // from the thread, which also means that TaskQueue::Current() must not
313 // return a pointer to the Thread instance.
314 current->ClearCurrentTaskQueue();
315 }
316 }
317
Sebastian Jansson178a6852020-01-14 11:12:26 +0100318 SetCurrentThreadInternal(thread);
319}
320
321void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
322 SetCurrentThreadInternal(thread);
323}
324
Yves Gerey665174f2018-06-19 15:03:05 +0200325Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800327 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100328 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000329 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330 }
331 return result;
332}
333
334void ThreadManager::UnwrapCurrentThread() {
335 Thread* t = CurrentThread();
336 if (t && !(t->IsOwned())) {
337 t->UnwrapCurrent();
338 delete t;
339 }
340}
341
Niels Moller9d1840c2019-05-21 07:26:37 +0000342bool ThreadManager::IsMainThread() {
343 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
344}
345
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000346Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200347 : thread_(Thread::Current()),
348 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000349
350Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800351 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000352 thread_->SetAllowBlockingCalls(previous_state_);
353}
354
Taylor Brandstetter08672602018-03-02 15:20:33 -0800355Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700356
357Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800358 : Thread(std::move(ss), /*do_init=*/true) {}
359
360Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100361 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100362 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100363 fInitialized_(false),
364 fDestroyed_(false),
365 stop_(0),
366 ss_(ss) {
367 RTC_DCHECK(ss);
368 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800369 SetName("Thread", this); // default name
370 if (do_init) {
371 DoInit();
372 }
373}
374
375Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100376 : Thread(ss.get(), do_init) {
377 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000378}
379
380Thread::~Thread() {
381 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800382 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000383}
384
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100385void Thread::DoInit() {
386 if (fInitialized_) {
387 return;
388 }
389
390 fInitialized_ = true;
391 ThreadManager::Add(this);
392}
393
394void Thread::DoDestroy() {
395 if (fDestroyed_) {
396 return;
397 }
398
399 fDestroyed_ = true;
400 // The signal is done from here to ensure
401 // that it always gets called when the queue
402 // is going away.
403 SignalQueueDestroyed();
404 ThreadManager::Remove(this);
405 ClearInternal(nullptr, MQID_ANY, nullptr);
406
407 if (ss_) {
408 ss_->SetMessageQueue(nullptr);
409 }
410}
411
412SocketServer* Thread::socketserver() {
413 return ss_;
414}
415
416void Thread::WakeUpSocketServer() {
417 ss_->WakeUp();
418}
419
420void Thread::Quit() {
421 AtomicOps::ReleaseStore(&stop_, 1);
422 WakeUpSocketServer();
423}
424
425bool Thread::IsQuitting() {
426 return AtomicOps::AcquireLoad(&stop_) != 0;
427}
428
429void Thread::Restart() {
430 AtomicOps::ReleaseStore(&stop_, 0);
431}
432
433bool Thread::Peek(Message* pmsg, int cmsWait) {
434 if (fPeekKeep_) {
435 *pmsg = msgPeek_;
436 return true;
437 }
438 if (!Get(pmsg, cmsWait))
439 return false;
440 msgPeek_ = *pmsg;
441 fPeekKeep_ = true;
442 return true;
443}
444
445bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
446 // Return and clear peek if present
447 // Always return the peek if it exists so there is Peek/Get symmetry
448
449 if (fPeekKeep_) {
450 *pmsg = msgPeek_;
451 fPeekKeep_ = false;
452 return true;
453 }
454
455 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
456
457 int64_t cmsTotal = cmsWait;
458 int64_t cmsElapsed = 0;
459 int64_t msStart = TimeMillis();
460 int64_t msCurrent = msStart;
461 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100462 // Check for posted events
463 int64_t cmsDelayNext = kForever;
464 bool first_pass = true;
465 while (true) {
466 // All queue operations need to be locked, but nothing else in this loop
467 // (specifically handling disposed message) can happen inside the crit.
468 // Otherwise, disposed MessageHandlers will cause deadlocks.
469 {
470 CritScope cs(&crit_);
471 // On the first pass, check for delayed messages that have been
472 // triggered and calculate the next trigger time.
473 if (first_pass) {
474 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100475 while (!delayed_messages_.empty()) {
476 if (msCurrent < delayed_messages_.top().run_time_ms_) {
477 cmsDelayNext =
478 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100479 break;
480 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100481 messages_.push_back(delayed_messages_.top().msg_);
482 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100483 }
484 }
485 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100486 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100487 break;
488 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100489 *pmsg = messages_.front();
490 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100491 }
492 } // crit_ is released here.
493
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100494 // If this was a dispose message, delete it and skip it.
495 if (MQID_DISPOSE == pmsg->message_id) {
496 RTC_DCHECK(nullptr == pmsg->phandler);
497 delete pmsg->pdata;
498 *pmsg = Message();
499 continue;
500 }
501 return true;
502 }
503
504 if (IsQuitting())
505 break;
506
507 // Which is shorter, the delay wait or the asked wait?
508
509 int64_t cmsNext;
510 if (cmsWait == kForever) {
511 cmsNext = cmsDelayNext;
512 } else {
513 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
514 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
515 cmsNext = cmsDelayNext;
516 }
517
518 {
519 // Wait and multiplex in the meantime
520 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
521 return false;
522 }
523
524 // If the specified timeout expired, return
525
526 msCurrent = TimeMillis();
527 cmsElapsed = TimeDiff(msCurrent, msStart);
528 if (cmsWait != kForever) {
529 if (cmsElapsed >= cmsWait)
530 return false;
531 }
532 }
533 return false;
534}
535
536void Thread::Post(const Location& posted_from,
537 MessageHandler* phandler,
538 uint32_t id,
539 MessageData* pdata,
540 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100541 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100542 if (IsQuitting()) {
543 delete pdata;
544 return;
545 }
546
547 // Keep thread safe
548 // Add the message to the end of the queue
549 // Signal for the multiplexer to return
550
551 {
552 CritScope cs(&crit_);
553 Message msg;
554 msg.posted_from = posted_from;
555 msg.phandler = phandler;
556 msg.message_id = id;
557 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100558 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100559 }
560 WakeUpSocketServer();
561}
562
563void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100564 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100565 MessageHandler* phandler,
566 uint32_t id,
567 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100568 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100569 pdata);
570}
571
572void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100573 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100574 MessageHandler* phandler,
575 uint32_t id,
576 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100577 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100578 pdata);
579}
580
581void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100582 int64_t delay_ms,
583 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100584 MessageHandler* phandler,
585 uint32_t id,
586 MessageData* pdata) {
587 if (IsQuitting()) {
588 delete pdata;
589 return;
590 }
591
592 // Keep thread safe
593 // Add to the priority queue. Gets sorted soonest first.
594 // Signal for the multiplexer to return.
595
596 {
597 CritScope cs(&crit_);
598 Message msg;
599 msg.posted_from = posted_from;
600 msg.phandler = phandler;
601 msg.message_id = id;
602 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100603 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
604 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100605 // If this message queue processes 1 message every millisecond for 50 days,
606 // we will wrap this number. Even then, only messages with identical times
607 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100608 ++delayed_next_num_;
609 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100610 }
611 WakeUpSocketServer();
612}
613
614int Thread::GetDelay() {
615 CritScope cs(&crit_);
616
Sebastian Jansson61380c02020-01-17 14:46:08 +0100617 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100618 return 0;
619
Sebastian Jansson61380c02020-01-17 14:46:08 +0100620 if (!delayed_messages_.empty()) {
621 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100622 if (delay < 0)
623 delay = 0;
624 return delay;
625 }
626
627 return kForever;
628}
629
630void Thread::ClearInternal(MessageHandler* phandler,
631 uint32_t id,
632 MessageList* removed) {
633 // Remove messages with phandler
634
635 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
636 if (removed) {
637 removed->push_back(msgPeek_);
638 } else {
639 delete msgPeek_.pdata;
640 }
641 fPeekKeep_ = false;
642 }
643
644 // Remove from ordered message queue
645
Sebastian Jansson61380c02020-01-17 14:46:08 +0100646 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100647 if (it->Match(phandler, id)) {
648 if (removed) {
649 removed->push_back(*it);
650 } else {
651 delete it->pdata;
652 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100653 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100654 } else {
655 ++it;
656 }
657 }
658
659 // Remove from priority queue. Not directly iterable, so use this approach
660
Sebastian Jansson61380c02020-01-17 14:46:08 +0100661 auto new_end = delayed_messages_.container().begin();
662 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100663 if (it->msg_.Match(phandler, id)) {
664 if (removed) {
665 removed->push_back(it->msg_);
666 } else {
667 delete it->msg_.pdata;
668 }
669 } else {
670 *new_end++ = *it;
671 }
672 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100673 delayed_messages_.container().erase(new_end,
674 delayed_messages_.container().end());
675 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100676}
677
678void Thread::Dispatch(Message* pmsg) {
679 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
680 pmsg->posted_from.file_name(), "src_func",
681 pmsg->posted_from.function_name());
Harald Alvestrandba694422021-01-27 21:52:14 +0000682 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100683 int64_t start_time = TimeMillis();
684 pmsg->phandler->OnMessage(pmsg);
685 int64_t end_time = TimeMillis();
686 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000687 if (diff >= dispatch_warning_ms_) {
688 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100689 << "ms to dispatch. Posted from: "
690 << pmsg->posted_from.ToString();
Harald Alvestrandba694422021-01-27 21:52:14 +0000691 // To avoid log spew, move the warning limit to only give warning
692 // for delays that are larger than the one observed.
693 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100694 }
695}
696
nisse7866cfe2017-04-26 01:45:31 -0700697bool Thread::IsCurrent() const {
698 return ThreadManager::Instance()->CurrentThread() == this;
699}
700
danilchapbebf54c2016-04-28 01:32:48 -0700701std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100702 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700703}
704
705std::unique_ptr<Thread> Thread::Create() {
706 return std::unique_ptr<Thread>(
707 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
708}
709
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000710bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000711 AssertBlockingIsAllowedOnCurrentThread();
712
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000713#if defined(WEBRTC_WIN)
714 ::Sleep(milliseconds);
715 return true;
716#else
717 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
718 // so we use nanosleep() even though it has greater precision than necessary.
719 struct timespec ts;
720 ts.tv_sec = milliseconds / 1000;
721 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800722 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000723 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100724 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000725 return false;
726 }
727 return true;
728#endif
729}
730
731bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100732 RTC_DCHECK(!IsRunning());
733
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000734 name_ = name;
735 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200736 // The %p specifier typically produce at most 16 hex digits, possibly with a
737 // 0x prefix. But format is implementation defined, so add some margin.
738 char buf[30];
739 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000740 name_ += buf;
741 }
742 return true;
743}
744
Harald Alvestrandba694422021-01-27 21:52:14 +0000745void Thread::SetDispatchWarningMs(int deadline) {
746 if (!IsCurrent()) {
747 PostTask(webrtc::ToQueuedTask(
748 [this, deadline]() { SetDispatchWarningMs(deadline); }));
749 return;
750 }
751 RTC_DCHECK_RUN_ON(this);
752 dispatch_warning_ms_ = deadline;
753}
754
Niels Möllerd2e50132019-06-11 09:24:14 +0200755bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100756 RTC_DCHECK(!IsRunning());
757
758 if (IsRunning())
759 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000760
André Susano Pinto02a57972016-07-22 13:30:05 +0200761 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000762
763 // Make sure that ThreadManager is created on the main thread before
764 // we start a new thread.
765 ThreadManager::Instance();
766
Tommi51492422017-12-04 15:18:23 +0100767 owned_ = true;
768
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000769#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200770 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100771 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000772 return false;
773 }
774#elif defined(WEBRTC_POSIX)
775 pthread_attr_t attr;
776 pthread_attr_init(&attr);
777
Niels Möllerd2e50132019-06-11 09:24:14 +0200778 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000779 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100780 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100781 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000782 return false;
783 }
Tommi51492422017-12-04 15:18:23 +0100784 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000785#endif
786 return true;
787}
788
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000789bool Thread::WrapCurrent() {
790 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
791}
792
793void Thread::UnwrapCurrent() {
794 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800795 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000796#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800797 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000798 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100799 RTC_LOG_GLE(LS_ERROR)
800 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000801 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800802 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100803 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000804 }
Tommi51492422017-12-04 15:18:23 +0100805#elif defined(WEBRTC_POSIX)
806 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000807#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000808}
809
810void Thread::SafeWrapCurrent() {
811 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
812}
813
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000814void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100815 if (!IsRunning())
816 return;
817
818 RTC_DCHECK(!IsCurrent());
819 if (Current() && !Current()->blocking_calls_allowed_) {
820 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100821 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100822 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000823
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000824#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100825 RTC_DCHECK(thread_ != nullptr);
826 WaitForSingleObject(thread_, INFINITE);
827 CloseHandle(thread_);
828 thread_ = nullptr;
829 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000830#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100831 pthread_join(thread_, nullptr);
832 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000833#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000834}
835
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000836bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800837 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000838 bool previous = blocking_calls_allowed_;
839 blocking_calls_allowed_ = allow;
840 return previous;
841}
842
843// static
844void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700845#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000846 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800847 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000848#endif
849}
850
deadbeefdc20e262017-01-31 15:10:44 -0800851// static
852#if defined(WEBRTC_WIN)
853DWORD WINAPI Thread::PreRun(LPVOID pv) {
854#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000855void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800856#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200857 Thread* thread = static_cast<Thread*>(pv);
858 ThreadManager::Instance()->SetCurrentThread(thread);
859 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200860#if defined(WEBRTC_MAC)
861 ScopedAutoReleasePool pool;
862#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200863 thread->Run();
864
Tommi51492422017-12-04 15:18:23 +0100865 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800866#ifdef WEBRTC_WIN
867 return 0;
868#else
869 return nullptr;
870#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200871} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000872
873void Thread::Run() {
874 ProcessMessages(kForever);
875}
876
877bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100878 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000879 return owned_;
880}
881
882void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100883 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000884 Join();
885}
886
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700887void Thread::Send(const Location& posted_from,
888 MessageHandler* phandler,
889 uint32_t id,
890 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100891 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200892 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000893 return;
894
895 // Sent messages are sent to the MessageHandler directly, in the context
896 // of "thread", like Win32 SendMessage. If in the right context,
897 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000898 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700899 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000900 msg.phandler = phandler;
901 msg.message_id = id;
902 msg.pdata = pdata;
903 if (IsCurrent()) {
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100904 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000905 return;
906 }
907
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000908 AssertBlockingIsAllowedOnCurrentThread();
909
Yves Gerey665174f2018-06-19 15:03:05 +0200910 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200911
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100912#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200913 if (current_thread) {
914 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
915 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
916 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000917 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200918#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000919
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200920 // Perhaps down the line we can get rid of this workaround and always require
921 // current_thread to be valid when Send() is called.
922 std::unique_ptr<rtc::Event> done_event;
923 if (!current_thread)
924 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000925
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200926 bool ready = false;
927 PostTask(webrtc::ToQueuedTask(
928 [&msg]() mutable { msg.phandler->OnMessage(&msg); },
929 [this, &ready, current_thread, done = done_event.get()] {
930 if (current_thread) {
931 CritScope cs(&crit_);
932 ready = true;
933 current_thread->socketserver()->WakeUp();
934 } else {
935 done->Set();
936 }
937 }));
938
939 if (current_thread) {
940 bool waited = false;
941 crit_.Enter();
942 while (!ready) {
943 crit_.Leave();
944 current_thread->socketserver()->Wait(kForever, false);
945 waited = true;
946 crit_.Enter();
947 }
948 crit_.Leave();
949
950 // Our Wait loop above may have consumed some WakeUp events for this
951 // Thread, that weren't relevant to this Send. Losing these WakeUps can
952 // cause problems for some SocketServers.
953 //
954 // Concrete example:
955 // Win32SocketServer on thread A calls Send on thread B. While processing
956 // the message, thread B Posts a message to A. We consume the wakeup for
957 // that Post while waiting for the Send to complete, which means that when
958 // we exit this loop, we need to issue another WakeUp, or else the Posted
959 // message won't be processed in a timely manner.
960
961 if (waited) {
962 current_thread->socketserver()->WakeUp();
963 }
964 } else {
965 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000966 }
967}
968
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700969void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100970 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800971 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
972 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100973
974 class FunctorMessageHandler : public MessageHandler {
975 public:
976 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +0200977 : functor_(functor) {}
Danil Chapovalov89313452019-11-29 12:56:43 +0100978 void OnMessage(Message* msg) override { functor_(); }
979
980 private:
981 rtc::FunctionView<void()> functor_;
982 } handler(functor);
983
984 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000985}
986
Tommi6866dc72020-05-15 10:11:56 +0200987// Called by the ThreadManager when being set as the current thread.
988void Thread::EnsureIsCurrentTaskQueue() {
989 task_queue_registration_ =
990 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
991}
992
993// Called by the ThreadManager when being set as the current thread.
994void Thread::ClearCurrentTaskQueue() {
995 task_queue_registration_.reset();
996}
997
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100998void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
999 RTC_DCHECK(msg);
1000 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
1001 std::unique_ptr<webrtc::QueuedTask> task = std::move(data->data());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001002 // Thread expects handler to own Message::pdata when OnMessage is called
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001003 // Since MessageData is no longer needed, delete it.
1004 delete data;
1005
1006 // QueuedTask interface uses Run return value to communicate who owns the
1007 // task. false means QueuedTask took the ownership.
1008 if (!task->Run())
1009 task.release();
1010}
1011
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001012void Thread::AllowInvokesToThread(Thread* thread) {
1013#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1014 if (!IsCurrent()) {
1015 PostTask(webrtc::ToQueuedTask(
1016 [thread, this]() { AllowInvokesToThread(thread); }));
1017 return;
1018 }
1019 RTC_DCHECK_RUN_ON(this);
1020 allowed_threads_.push_back(thread);
1021 invoke_policy_enabled_ = true;
1022#endif
1023}
1024
1025void Thread::DisallowAllInvokes() {
1026#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1027 if (!IsCurrent()) {
1028 PostTask(webrtc::ToQueuedTask([this]() { DisallowAllInvokes(); }));
1029 return;
1030 }
1031 RTC_DCHECK_RUN_ON(this);
1032 allowed_threads_.clear();
1033 invoke_policy_enabled_ = true;
1034#endif
1035}
1036
1037// Returns true if no policies added or if there is at least one policy
1038// that permits invocation to |target| thread.
1039bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
1040#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1041 RTC_DCHECK_RUN_ON(this);
1042 if (!invoke_policy_enabled_) {
1043 return true;
1044 }
1045 for (const auto* thread : allowed_threads_) {
1046 if (thread == target) {
1047 return true;
1048 }
1049 }
1050 return false;
1051#else
1052 return true;
1053#endif
1054}
1055
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001056void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
1057 // Though Post takes MessageData by raw pointer (last parameter), it still
1058 // takes it with ownership.
1059 Post(RTC_FROM_HERE, &queued_task_handler_,
1060 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1061}
1062
1063void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
1064 uint32_t milliseconds) {
1065 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1066 // it still takes it with ownership.
1067 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
1068 /*id=*/0,
1069 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1070}
1071
1072void Thread::Delete() {
1073 Stop();
1074 delete this;
1075}
1076
Niels Möller8909a632018-09-06 08:42:44 +02001077bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001078 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001079}
1080
Peter Boström0c4e06b2015-10-07 12:23:21 +02001081void Thread::Clear(MessageHandler* phandler,
1082 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001083 MessageList* removed) {
1084 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001085 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001086}
1087
1088bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001089 // Using ProcessMessages with a custom clock for testing and a time greater
1090 // than 0 doesn't work, since it's not guaranteed to advance the custom
1091 // clock's time, and may get stuck in an infinite loop.
1092 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1093 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001094 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001095 int cmsNext = cmsLoop;
1096
1097 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001098#if defined(WEBRTC_MAC)
1099 ScopedAutoReleasePool pool;
1100#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001101 Message msg;
1102 if (!Get(&msg, cmsNext))
1103 return !IsQuitting();
1104 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001105
kthelgasonde6adbe2017-02-22 00:42:11 -08001106 if (cmsLoop != kForever) {
1107 cmsNext = static_cast<int>(TimeUntil(msEnd));
1108 if (cmsNext < 0)
1109 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001110 }
1111 }
1112}
1113
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001114bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1115 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001116 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001117
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001118#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001119 if (need_synchronize_access) {
1120 // We explicitly ask for no rights other than synchronization.
1121 // This gives us the best chance of succeeding.
1122 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1123 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001124 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001125 return false;
1126 }
1127 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001128 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001129#elif defined(WEBRTC_POSIX)
1130 thread_ = pthread_self();
1131#endif
1132 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001133 thread_manager->SetCurrentThread(this);
1134 return true;
1135}
1136
Tommi51492422017-12-04 15:18:23 +01001137bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001138#if defined(WEBRTC_WIN)
1139 return thread_ != nullptr;
1140#elif defined(WEBRTC_POSIX)
1141 return thread_ != 0;
1142#endif
1143}
1144
Steve Antonbcc1a762019-12-11 11:21:53 -08001145// static
1146MessageHandler* Thread::GetPostTaskMessageHandler() {
1147 // Allocate at first call, never deallocate.
1148 static MessageHandler* handler = new MessageHandlerWithTask;
1149 return handler;
1150}
1151
Taylor Brandstetter08672602018-03-02 15:20:33 -08001152AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +01001153 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001154 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001155 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001156 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1157 // post a message to a queue that no running thread is serving.
1158 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001159 ThreadManager::Instance()->SetCurrentThread(this);
1160 }
1161}
1162
1163AutoThread::~AutoThread() {
1164 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001165 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001166 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001167 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001168 }
1169}
1170
nisse7eaa4ea2017-05-08 05:25:41 -07001171AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001172 : Thread(ss, /*do_init=*/false) {
1173 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001174 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001175 // Temporarily set the current thread to nullptr so that we can keep checks
1176 // around that catch unintentional pointer overwrites.
1177 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001178 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1179 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001180 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001181 }
1182}
1183
1184AutoSocketServerThread::~AutoSocketServerThread() {
1185 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
1186 // Some tests post destroy messages to this thread. To avoid memory
1187 // leaks, we have to process those messages. In particular
1188 // P2PTransportChannelPingTest, relying on the message posted in
1189 // cricket::Connection::Destroy.
1190 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -07001191 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001192 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001193 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1194 // its contents rely on this thread still being set as the current thread.
1195 Stop();
1196 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001197 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001198 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1199 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001200 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001201 }
1202}
1203
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001204} // namespace rtc