blob: 2882f50da3e2e65d1d800246dac7866574c10d3a [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "rtc_base/null_socket_server.h"
Artem Titovdfc5f0d2020-07-03 12:09:26 +020037#include "rtc_base/synchronization/sequence_checker.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010038#include "rtc_base/task_utils/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020042#if defined(WEBRTC_MAC)
43#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020044
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020045/*
46 * These are forward-declarations for methods that are part of the
47 * ObjC runtime. They are declared in the private header objc-internal.h.
48 * These calls are what clang inserts when using @autoreleasepool in ObjC,
49 * but here they are used directly in order to keep this file C++.
50 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
51 */
52extern "C" {
53void* objc_autoreleasePoolPush(void);
54void objc_autoreleasePoolPop(void* pool);
55}
56
57namespace {
58class ScopedAutoReleasePool {
59 public:
60 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
61 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
62
63 private:
64 void* const pool_;
65};
66} // namespace
67#endif
68
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080070namespace {
71
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010072const int kSlowDispatchLoggingThreshold = 50; // 50 ms
73
Steve Antonbcc1a762019-12-11 11:21:53 -080074class MessageHandlerWithTask final : public MessageHandler {
75 public:
76 MessageHandlerWithTask() = default;
77
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) {
167 CritScope cs(&crit_);
168 std::deque<Thread*> all_targets({target});
169 // We check the pre-existing who-sends-to-who graph for any path from target
170 // to source. This loop is guaranteed to terminate because per the send graph
171 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800172 for (size_t i = 0; i < all_targets.size(); i++) {
173 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100174 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
175 }
176 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
177 << " send loop between " << source->name() << " and " << target->name();
178
179 // We may now insert source -> target without creating a cycle, since there
180 // was no path from target to source per the prior CHECK.
181 send_graph_[source].insert(target);
182}
183#endif
184
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100185// static
186void ThreadManager::Clear(MessageHandler* handler) {
187 return Instance()->ClearInternal(handler);
188}
189void ThreadManager::ClearInternal(MessageHandler* handler) {
190 // Deleted objects may cause re-entrant calls to ClearInternal. This is
191 // allowed as the list of message queues does not change while queues are
192 // cleared.
193 MarkProcessingCritScope cs(&crit_, &processing_);
194 for (Thread* queue : message_queues_) {
195 queue->Clear(handler);
196 }
197}
198
199// static
200void ThreadManager::ProcessAllMessageQueuesForTesting() {
201 return Instance()->ProcessAllMessageQueuesInternal();
202}
203
204void ThreadManager::ProcessAllMessageQueuesInternal() {
205 // This works by posting a delayed message at the current time and waiting
206 // for it to be dispatched on all queues, which will ensure that all messages
207 // that came before it were also dispatched.
208 volatile int queues_not_done = 0;
209
210 // This class is used so that whether the posted message is processed, or the
211 // message queue is simply cleared, queues_not_done gets decremented.
212 class ScopedIncrement : public MessageData {
213 public:
214 ScopedIncrement(volatile int* value) : value_(value) {
215 AtomicOps::Increment(value_);
216 }
217 ~ScopedIncrement() override { AtomicOps::Decrement(value_); }
218
219 private:
220 volatile int* value_;
221 };
222
223 {
224 MarkProcessingCritScope cs(&crit_, &processing_);
225 for (Thread* queue : message_queues_) {
226 if (!queue->IsProcessingMessagesForTesting()) {
227 // If the queue is not processing messages, it can
228 // be ignored. If we tried to post a message to it, it would be dropped
229 // or ignored.
230 continue;
231 }
232 queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
233 new ScopedIncrement(&queues_not_done));
234 }
235 }
236
237 rtc::Thread* current = rtc::Thread::Current();
238 // Note: One of the message queues may have been on this thread, which is
239 // why we can't synchronously wait for queues_not_done to go to 0; we need
240 // to process messages as well.
241 while (AtomicOps::AcquireLoad(&queues_not_done) > 0) {
242 if (current) {
243 current->ProcessMessages(0);
244 }
245 }
246}
247
248// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700250 ThreadManager* manager = ThreadManager::Instance();
251 Thread* thread = manager->CurrentThread();
252
Niels Moller9d1840c2019-05-21 07:26:37 +0000253#ifndef NO_MAIN_THREAD_WRAPPING
254 // Only autowrap the thread which instantiated the ThreadManager.
255 if (!thread && manager->IsMainThread()) {
256 thread = new Thread(SocketServer::CreateDefault());
257 thread->WrapCurrentWithThreadManager(manager, true);
258 }
259#endif
260
nisse7866cfe2017-04-26 01:45:31 -0700261 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262}
263
264#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +0000265ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200266#if defined(WEBRTC_MAC)
267 InitCocoaMultiThreading();
268#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800269 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270}
271
Yves Gerey665174f2018-06-19 15:03:05 +0200272Thread* ThreadManager::CurrentThread() {
273 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000274}
275
Sebastian Jansson178a6852020-01-14 11:12:26 +0100276void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277 pthread_setspecific(key_, thread);
278}
279#endif
280
281#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000282ThreadManager::ThreadManager()
283 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200284
285Thread* ThreadManager::CurrentThread() {
286 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287}
288
Sebastian Jansson178a6852020-01-14 11:12:26 +0100289void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290 TlsSetValue(key_, thread);
291}
292#endif
293
Sebastian Jansson178a6852020-01-14 11:12:26 +0100294void ThreadManager::SetCurrentThread(Thread* thread) {
295#if RTC_DLOG_IS_ON
296 if (CurrentThread() && thread) {
297 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
298 }
299#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200300
301 if (thread) {
302 thread->EnsureIsCurrentTaskQueue();
303 } else {
304 Thread* current = CurrentThread();
305 if (current) {
306 // The current thread is being cleared, e.g. as a result of
307 // UnwrapCurrent() being called or when a thread is being stopped
308 // (see PreRun()). This signals that the Thread instance is being detached
309 // from the thread, which also means that TaskQueue::Current() must not
310 // return a pointer to the Thread instance.
311 current->ClearCurrentTaskQueue();
312 }
313 }
314
Sebastian Jansson178a6852020-01-14 11:12:26 +0100315 SetCurrentThreadInternal(thread);
316}
317
318void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
319 SetCurrentThreadInternal(thread);
320}
321
Yves Gerey665174f2018-06-19 15:03:05 +0200322Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800324 if (nullptr == result) {
tommie7251592017-07-14 14:44:46 -0700325 result = new Thread(SocketServer::CreateDefault());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000326 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000327 }
328 return result;
329}
330
331void ThreadManager::UnwrapCurrentThread() {
332 Thread* t = CurrentThread();
333 if (t && !(t->IsOwned())) {
334 t->UnwrapCurrent();
335 delete t;
336 }
337}
338
Niels Moller9d1840c2019-05-21 07:26:37 +0000339bool ThreadManager::IsMainThread() {
340 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
341}
342
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000343Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200344 : thread_(Thread::Current()),
345 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000346
347Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800348 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000349 thread_->SetAllowBlockingCalls(previous_state_);
350}
351
Taylor Brandstetter08672602018-03-02 15:20:33 -0800352Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700353
354Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800355 : Thread(std::move(ss), /*do_init=*/true) {}
356
357Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100358 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100359 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100360 fInitialized_(false),
361 fDestroyed_(false),
362 stop_(0),
363 ss_(ss) {
364 RTC_DCHECK(ss);
365 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800366 SetName("Thread", this); // default name
367 if (do_init) {
368 DoInit();
369 }
370}
371
372Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100373 : Thread(ss.get(), do_init) {
374 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375}
376
377Thread::~Thread() {
378 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800379 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000380}
381
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100382void Thread::DoInit() {
383 if (fInitialized_) {
384 return;
385 }
386
387 fInitialized_ = true;
388 ThreadManager::Add(this);
389}
390
391void Thread::DoDestroy() {
392 if (fDestroyed_) {
393 return;
394 }
395
396 fDestroyed_ = true;
397 // The signal is done from here to ensure
398 // that it always gets called when the queue
399 // is going away.
400 SignalQueueDestroyed();
401 ThreadManager::Remove(this);
402 ClearInternal(nullptr, MQID_ANY, nullptr);
403
404 if (ss_) {
405 ss_->SetMessageQueue(nullptr);
406 }
407}
408
409SocketServer* Thread::socketserver() {
410 return ss_;
411}
412
413void Thread::WakeUpSocketServer() {
414 ss_->WakeUp();
415}
416
417void Thread::Quit() {
418 AtomicOps::ReleaseStore(&stop_, 1);
419 WakeUpSocketServer();
420}
421
422bool Thread::IsQuitting() {
423 return AtomicOps::AcquireLoad(&stop_) != 0;
424}
425
426void Thread::Restart() {
427 AtomicOps::ReleaseStore(&stop_, 0);
428}
429
430bool Thread::Peek(Message* pmsg, int cmsWait) {
431 if (fPeekKeep_) {
432 *pmsg = msgPeek_;
433 return true;
434 }
435 if (!Get(pmsg, cmsWait))
436 return false;
437 msgPeek_ = *pmsg;
438 fPeekKeep_ = true;
439 return true;
440}
441
442bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
443 // Return and clear peek if present
444 // Always return the peek if it exists so there is Peek/Get symmetry
445
446 if (fPeekKeep_) {
447 *pmsg = msgPeek_;
448 fPeekKeep_ = false;
449 return true;
450 }
451
452 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
453
454 int64_t cmsTotal = cmsWait;
455 int64_t cmsElapsed = 0;
456 int64_t msStart = TimeMillis();
457 int64_t msCurrent = msStart;
458 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100459 // Check for posted events
460 int64_t cmsDelayNext = kForever;
461 bool first_pass = true;
462 while (true) {
463 // All queue operations need to be locked, but nothing else in this loop
464 // (specifically handling disposed message) can happen inside the crit.
465 // Otherwise, disposed MessageHandlers will cause deadlocks.
466 {
467 CritScope cs(&crit_);
468 // On the first pass, check for delayed messages that have been
469 // triggered and calculate the next trigger time.
470 if (first_pass) {
471 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100472 while (!delayed_messages_.empty()) {
473 if (msCurrent < delayed_messages_.top().run_time_ms_) {
474 cmsDelayNext =
475 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100476 break;
477 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100478 messages_.push_back(delayed_messages_.top().msg_);
479 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100480 }
481 }
482 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100483 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100484 break;
485 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100486 *pmsg = messages_.front();
487 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100488 }
489 } // crit_ is released here.
490
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100491 // If this was a dispose message, delete it and skip it.
492 if (MQID_DISPOSE == pmsg->message_id) {
493 RTC_DCHECK(nullptr == pmsg->phandler);
494 delete pmsg->pdata;
495 *pmsg = Message();
496 continue;
497 }
498 return true;
499 }
500
501 if (IsQuitting())
502 break;
503
504 // Which is shorter, the delay wait or the asked wait?
505
506 int64_t cmsNext;
507 if (cmsWait == kForever) {
508 cmsNext = cmsDelayNext;
509 } else {
510 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
511 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
512 cmsNext = cmsDelayNext;
513 }
514
515 {
516 // Wait and multiplex in the meantime
517 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
518 return false;
519 }
520
521 // If the specified timeout expired, return
522
523 msCurrent = TimeMillis();
524 cmsElapsed = TimeDiff(msCurrent, msStart);
525 if (cmsWait != kForever) {
526 if (cmsElapsed >= cmsWait)
527 return false;
528 }
529 }
530 return false;
531}
532
533void Thread::Post(const Location& posted_from,
534 MessageHandler* phandler,
535 uint32_t id,
536 MessageData* pdata,
537 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100538 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100539 if (IsQuitting()) {
540 delete pdata;
541 return;
542 }
543
544 // Keep thread safe
545 // Add the message to the end of the queue
546 // Signal for the multiplexer to return
547
548 {
549 CritScope cs(&crit_);
550 Message msg;
551 msg.posted_from = posted_from;
552 msg.phandler = phandler;
553 msg.message_id = id;
554 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100555 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100556 }
557 WakeUpSocketServer();
558}
559
560void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100561 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100562 MessageHandler* phandler,
563 uint32_t id,
564 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100565 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100566 pdata);
567}
568
569void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100570 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100571 MessageHandler* phandler,
572 uint32_t id,
573 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100574 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100575 pdata);
576}
577
578void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100579 int64_t delay_ms,
580 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100581 MessageHandler* phandler,
582 uint32_t id,
583 MessageData* pdata) {
584 if (IsQuitting()) {
585 delete pdata;
586 return;
587 }
588
589 // Keep thread safe
590 // Add to the priority queue. Gets sorted soonest first.
591 // Signal for the multiplexer to return.
592
593 {
594 CritScope cs(&crit_);
595 Message msg;
596 msg.posted_from = posted_from;
597 msg.phandler = phandler;
598 msg.message_id = id;
599 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100600 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
601 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100602 // If this message queue processes 1 message every millisecond for 50 days,
603 // we will wrap this number. Even then, only messages with identical times
604 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100605 ++delayed_next_num_;
606 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100607 }
608 WakeUpSocketServer();
609}
610
611int Thread::GetDelay() {
612 CritScope cs(&crit_);
613
Sebastian Jansson61380c02020-01-17 14:46:08 +0100614 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100615 return 0;
616
Sebastian Jansson61380c02020-01-17 14:46:08 +0100617 if (!delayed_messages_.empty()) {
618 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100619 if (delay < 0)
620 delay = 0;
621 return delay;
622 }
623
624 return kForever;
625}
626
627void Thread::ClearInternal(MessageHandler* phandler,
628 uint32_t id,
629 MessageList* removed) {
630 // Remove messages with phandler
631
632 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
633 if (removed) {
634 removed->push_back(msgPeek_);
635 } else {
636 delete msgPeek_.pdata;
637 }
638 fPeekKeep_ = false;
639 }
640
641 // Remove from ordered message queue
642
Sebastian Jansson61380c02020-01-17 14:46:08 +0100643 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100644 if (it->Match(phandler, id)) {
645 if (removed) {
646 removed->push_back(*it);
647 } else {
648 delete it->pdata;
649 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100650 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100651 } else {
652 ++it;
653 }
654 }
655
656 // Remove from priority queue. Not directly iterable, so use this approach
657
Sebastian Jansson61380c02020-01-17 14:46:08 +0100658 auto new_end = delayed_messages_.container().begin();
659 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100660 if (it->msg_.Match(phandler, id)) {
661 if (removed) {
662 removed->push_back(it->msg_);
663 } else {
664 delete it->msg_.pdata;
665 }
666 } else {
667 *new_end++ = *it;
668 }
669 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100670 delayed_messages_.container().erase(new_end,
671 delayed_messages_.container().end());
672 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100673}
674
675void Thread::Dispatch(Message* pmsg) {
676 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
677 pmsg->posted_from.file_name(), "src_func",
678 pmsg->posted_from.function_name());
679 int64_t start_time = TimeMillis();
680 pmsg->phandler->OnMessage(pmsg);
681 int64_t end_time = TimeMillis();
682 int64_t diff = TimeDiff(end_time, start_time);
683 if (diff >= kSlowDispatchLoggingThreshold) {
684 RTC_LOG(LS_INFO) << "Message took " << diff
685 << "ms to dispatch. Posted from: "
686 << pmsg->posted_from.ToString();
687 }
688}
689
nisse7866cfe2017-04-26 01:45:31 -0700690bool Thread::IsCurrent() const {
691 return ThreadManager::Instance()->CurrentThread() == this;
692}
693
danilchapbebf54c2016-04-28 01:32:48 -0700694std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
695 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
696}
697
698std::unique_ptr<Thread> Thread::Create() {
699 return std::unique_ptr<Thread>(
700 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
701}
702
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000703bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000704 AssertBlockingIsAllowedOnCurrentThread();
705
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000706#if defined(WEBRTC_WIN)
707 ::Sleep(milliseconds);
708 return true;
709#else
710 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
711 // so we use nanosleep() even though it has greater precision than necessary.
712 struct timespec ts;
713 ts.tv_sec = milliseconds / 1000;
714 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800715 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000716 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100717 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000718 return false;
719 }
720 return true;
721#endif
722}
723
724bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100725 RTC_DCHECK(!IsRunning());
726
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000727 name_ = name;
728 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200729 // The %p specifier typically produce at most 16 hex digits, possibly with a
730 // 0x prefix. But format is implementation defined, so add some margin.
731 char buf[30];
732 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000733 name_ += buf;
734 }
735 return true;
736}
737
Niels Möllerd2e50132019-06-11 09:24:14 +0200738bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100739 RTC_DCHECK(!IsRunning());
740
741 if (IsRunning())
742 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000743
André Susano Pinto02a57972016-07-22 13:30:05 +0200744 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000745
746 // Make sure that ThreadManager is created on the main thread before
747 // we start a new thread.
748 ThreadManager::Instance();
749
Tommi51492422017-12-04 15:18:23 +0100750 owned_ = true;
751
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000752#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200753 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100754 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000755 return false;
756 }
757#elif defined(WEBRTC_POSIX)
758 pthread_attr_t attr;
759 pthread_attr_init(&attr);
760
Niels Möllerd2e50132019-06-11 09:24:14 +0200761 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000762 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100763 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100764 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000765 return false;
766 }
Tommi51492422017-12-04 15:18:23 +0100767 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000768#endif
769 return true;
770}
771
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000772bool Thread::WrapCurrent() {
773 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
774}
775
776void Thread::UnwrapCurrent() {
777 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800778 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000779#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800780 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000781 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100782 RTC_LOG_GLE(LS_ERROR)
783 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000784 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800785 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100786 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000787 }
Tommi51492422017-12-04 15:18:23 +0100788#elif defined(WEBRTC_POSIX)
789 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000790#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000791}
792
793void Thread::SafeWrapCurrent() {
794 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
795}
796
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000797void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100798 if (!IsRunning())
799 return;
800
801 RTC_DCHECK(!IsCurrent());
802 if (Current() && !Current()->blocking_calls_allowed_) {
803 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100804 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100805 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000806
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000807#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100808 RTC_DCHECK(thread_ != nullptr);
809 WaitForSingleObject(thread_, INFINITE);
810 CloseHandle(thread_);
811 thread_ = nullptr;
812 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000813#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100814 pthread_join(thread_, nullptr);
815 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000816#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000817}
818
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000819bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800820 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000821 bool previous = blocking_calls_allowed_;
822 blocking_calls_allowed_ = allow;
823 return previous;
824}
825
826// static
827void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700828#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000829 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800830 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000831#endif
832}
833
deadbeefdc20e262017-01-31 15:10:44 -0800834// static
835#if defined(WEBRTC_WIN)
836DWORD WINAPI Thread::PreRun(LPVOID pv) {
837#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000838void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800839#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200840 Thread* thread = static_cast<Thread*>(pv);
841 ThreadManager::Instance()->SetCurrentThread(thread);
842 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200843#if defined(WEBRTC_MAC)
844 ScopedAutoReleasePool pool;
845#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200846 thread->Run();
847
Tommi51492422017-12-04 15:18:23 +0100848 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800849#ifdef WEBRTC_WIN
850 return 0;
851#else
852 return nullptr;
853#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200854} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000855
856void Thread::Run() {
857 ProcessMessages(kForever);
858}
859
860bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100861 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000862 return owned_;
863}
864
865void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100866 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000867 Join();
868}
869
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700870void Thread::Send(const Location& posted_from,
871 MessageHandler* phandler,
872 uint32_t id,
873 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100874 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200875 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000876 return;
877
878 // Sent messages are sent to the MessageHandler directly, in the context
879 // of "thread", like Win32 SendMessage. If in the right context,
880 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000881 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700882 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000883 msg.phandler = phandler;
884 msg.message_id = id;
885 msg.pdata = pdata;
886 if (IsCurrent()) {
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100887 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000888 return;
889 }
890
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000891 AssertBlockingIsAllowedOnCurrentThread();
892
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000893 AutoThread thread;
Yves Gerey665174f2018-06-19 15:03:05 +0200894 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800895 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200896 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100897#if RTC_DCHECK_IS_ON
898 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
899 this);
900#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000901 bool ready = false;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100902 PostTask(
903 webrtc::ToQueuedTask([msg]() mutable { msg.phandler->OnMessage(&msg); },
904 [this, &ready, current_thread] {
905 CritScope cs(&crit_);
906 ready = true;
907 current_thread->socketserver()->WakeUp();
908 }));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000909
910 bool waited = false;
911 crit_.Enter();
912 while (!ready) {
913 crit_.Leave();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000914 current_thread->socketserver()->Wait(kForever, false);
915 waited = true;
916 crit_.Enter();
917 }
918 crit_.Leave();
919
920 // Our Wait loop above may have consumed some WakeUp events for this
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100921 // Thread, that weren't relevant to this Send. Losing these WakeUps can
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000922 // cause problems for some SocketServers.
923 //
924 // Concrete example:
925 // Win32SocketServer on thread A calls Send on thread B. While processing the
926 // message, thread B Posts a message to A. We consume the wakeup for that
927 // Post while waiting for the Send to complete, which means that when we exit
928 // this loop, we need to issue another WakeUp, or else the Posted message
929 // won't be processed in a timely manner.
930
931 if (waited) {
932 current_thread->socketserver()->WakeUp();
933 }
934}
935
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700936void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100937 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800938 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
939 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100940
941 class FunctorMessageHandler : public MessageHandler {
942 public:
943 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
944 : functor_(functor) {}
945 void OnMessage(Message* msg) override { functor_(); }
946
947 private:
948 rtc::FunctionView<void()> functor_;
949 } handler(functor);
950
951 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000952}
953
Tommi6866dc72020-05-15 10:11:56 +0200954// Called by the ThreadManager when being set as the current thread.
955void Thread::EnsureIsCurrentTaskQueue() {
956 task_queue_registration_ =
957 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
958}
959
960// Called by the ThreadManager when being set as the current thread.
961void Thread::ClearCurrentTaskQueue() {
962 task_queue_registration_.reset();
963}
964
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100965void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
966 RTC_DCHECK(msg);
967 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
968 std::unique_ptr<webrtc::QueuedTask> task = std::move(data->data());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100969 // Thread expects handler to own Message::pdata when OnMessage is called
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100970 // Since MessageData is no longer needed, delete it.
971 delete data;
972
973 // QueuedTask interface uses Run return value to communicate who owns the
974 // task. false means QueuedTask took the ownership.
975 if (!task->Run())
976 task.release();
977}
978
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200979void Thread::AllowInvokesToThread(Thread* thread) {
980#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
981 if (!IsCurrent()) {
982 PostTask(webrtc::ToQueuedTask(
983 [thread, this]() { AllowInvokesToThread(thread); }));
984 return;
985 }
986 RTC_DCHECK_RUN_ON(this);
987 allowed_threads_.push_back(thread);
988 invoke_policy_enabled_ = true;
989#endif
990}
991
992void Thread::DisallowAllInvokes() {
993#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
994 if (!IsCurrent()) {
995 PostTask(webrtc::ToQueuedTask([this]() { DisallowAllInvokes(); }));
996 return;
997 }
998 RTC_DCHECK_RUN_ON(this);
999 allowed_threads_.clear();
1000 invoke_policy_enabled_ = true;
1001#endif
1002}
1003
1004// Returns true if no policies added or if there is at least one policy
1005// that permits invocation to |target| thread.
1006bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
1007#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1008 RTC_DCHECK_RUN_ON(this);
1009 if (!invoke_policy_enabled_) {
1010 return true;
1011 }
1012 for (const auto* thread : allowed_threads_) {
1013 if (thread == target) {
1014 return true;
1015 }
1016 }
1017 return false;
1018#else
1019 return true;
1020#endif
1021}
1022
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001023void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
1024 // Though Post takes MessageData by raw pointer (last parameter), it still
1025 // takes it with ownership.
1026 Post(RTC_FROM_HERE, &queued_task_handler_,
1027 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1028}
1029
1030void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
1031 uint32_t milliseconds) {
1032 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1033 // it still takes it with ownership.
1034 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
1035 /*id=*/0,
1036 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1037}
1038
1039void Thread::Delete() {
1040 Stop();
1041 delete this;
1042}
1043
Niels Möller8909a632018-09-06 08:42:44 +02001044bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001045 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001046}
1047
Peter Boström0c4e06b2015-10-07 12:23:21 +02001048void Thread::Clear(MessageHandler* phandler,
1049 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001050 MessageList* removed) {
1051 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001052 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001053}
1054
1055bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001056 // Using ProcessMessages with a custom clock for testing and a time greater
1057 // than 0 doesn't work, since it's not guaranteed to advance the custom
1058 // clock's time, and may get stuck in an infinite loop.
1059 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1060 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001061 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001062 int cmsNext = cmsLoop;
1063
1064 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001065#if defined(WEBRTC_MAC)
1066 ScopedAutoReleasePool pool;
1067#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001068 Message msg;
1069 if (!Get(&msg, cmsNext))
1070 return !IsQuitting();
1071 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001072
kthelgasonde6adbe2017-02-22 00:42:11 -08001073 if (cmsLoop != kForever) {
1074 cmsNext = static_cast<int>(TimeUntil(msEnd));
1075 if (cmsNext < 0)
1076 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001077 }
1078 }
1079}
1080
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001081bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1082 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001083 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001084
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001085#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001086 if (need_synchronize_access) {
1087 // We explicitly ask for no rights other than synchronization.
1088 // This gives us the best chance of succeeding.
1089 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1090 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001091 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001092 return false;
1093 }
1094 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001095 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001096#elif defined(WEBRTC_POSIX)
1097 thread_ = pthread_self();
1098#endif
1099 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001100 thread_manager->SetCurrentThread(this);
1101 return true;
1102}
1103
Tommi51492422017-12-04 15:18:23 +01001104bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001105#if defined(WEBRTC_WIN)
1106 return thread_ != nullptr;
1107#elif defined(WEBRTC_POSIX)
1108 return thread_ != 0;
1109#endif
1110}
1111
Steve Antonbcc1a762019-12-11 11:21:53 -08001112// static
1113MessageHandler* Thread::GetPostTaskMessageHandler() {
1114 // Allocate at first call, never deallocate.
1115 static MessageHandler* handler = new MessageHandlerWithTask;
1116 return handler;
1117}
1118
Taylor Brandstetter08672602018-03-02 15:20:33 -08001119AutoThread::AutoThread()
1120 : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001121 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001122 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001123 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1124 // post a message to a queue that no running thread is serving.
1125 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001126 ThreadManager::Instance()->SetCurrentThread(this);
1127 }
1128}
1129
1130AutoThread::~AutoThread() {
1131 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001132 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001133 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001134 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001135 }
1136}
1137
nisse7eaa4ea2017-05-08 05:25:41 -07001138AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001139 : Thread(ss, /*do_init=*/false) {
1140 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001141 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001142 // Temporarily set the current thread to nullptr so that we can keep checks
1143 // around that catch unintentional pointer overwrites.
1144 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001145 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1146 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001147 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001148 }
1149}
1150
1151AutoSocketServerThread::~AutoSocketServerThread() {
1152 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
1153 // Some tests post destroy messages to this thread. To avoid memory
1154 // leaks, we have to process those messages. In particular
1155 // P2PTransportChannelPingTest, relying on the message posted in
1156 // cricket::Connection::Destroy.
1157 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -07001158 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001159 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001160 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1161 // its contents rely on this thread still being set as the current thread.
1162 Stop();
1163 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001164 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001165 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1166 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001167 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001168 }
1169}
1170
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001171} // namespace rtc