blob: fd104009d8c742ded5a8d56627e003791aa277c7 [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 Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080037#include "rtc_base/null_socket_server.h"
Artem Titovdfc5f0d2020-07-03 12:09:26 +020038#include "rtc_base/synchronization/sequence_checker.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010039#include "rtc_base/task_utils/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020043#if defined(WEBRTC_MAC)
44#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020045
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020046/*
47 * These are forward-declarations for methods that are part of the
48 * ObjC runtime. They are declared in the private header objc-internal.h.
49 * These calls are what clang inserts when using @autoreleasepool in ObjC,
50 * but here they are used directly in order to keep this file C++.
51 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
52 */
53extern "C" {
54void* objc_autoreleasePoolPush(void);
55void objc_autoreleasePoolPop(void* pool);
56}
57
58namespace {
59class ScopedAutoReleasePool {
60 public:
61 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
62 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
63
64 private:
65 void* const pool_;
66};
67} // namespace
68#endif
69
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080071namespace {
72
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010073const int kSlowDispatchLoggingThreshold = 50; // 50 ms
74
Steve Antonbcc1a762019-12-11 11:21:53 -080075class MessageHandlerWithTask final : public MessageHandler {
76 public:
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +020077 MessageHandlerWithTask() : MessageHandler(false) {}
Steve Antonbcc1a762019-12-11 11:21:53 -080078
79 void OnMessage(Message* msg) override {
80 static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
81 delete msg->pdata;
82 }
83
84 private:
85 ~MessageHandlerWithTask() override {}
86
87 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
88};
89
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010090class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
91 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020092 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
93 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010094 : cs_(cs), processing_(processing) {
95 cs_->Enter();
96 *processing_ += 1;
97 }
98
99 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
100 *processing_ -= 1;
101 cs_->Leave();
102 }
103
104 private:
Markus Handell3cb525b2020-07-16 16:16:09 +0200105 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100106 size_t* processing_;
107
108 RTC_DISALLOW_COPY_AND_ASSIGN(MarkProcessingCritScope);
109};
110
Steve Antonbcc1a762019-12-11 11:21:53 -0800111} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000112
113ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200114 static ThreadManager* const thread_manager = new ThreadManager();
115 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116}
117
nisse7866cfe2017-04-26 01:45:31 -0700118ThreadManager::~ThreadManager() {
119 // By above RTC_DEFINE_STATIC_LOCAL.
120 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
121}
122
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000123// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100124void ThreadManager::Add(Thread* message_queue) {
125 return Instance()->AddInternal(message_queue);
126}
127void ThreadManager::AddInternal(Thread* message_queue) {
128 CritScope cs(&crit_);
129 // Prevent changes while the list of message queues is processed.
130 RTC_DCHECK_EQ(processing_, 0);
131 message_queues_.push_back(message_queue);
132}
133
134// static
135void ThreadManager::Remove(Thread* message_queue) {
136 return Instance()->RemoveInternal(message_queue);
137}
138void ThreadManager::RemoveInternal(Thread* message_queue) {
139 {
140 CritScope cs(&crit_);
141 // Prevent changes while the list of message queues is processed.
142 RTC_DCHECK_EQ(processing_, 0);
143 std::vector<Thread*>::iterator iter;
144 iter = absl::c_find(message_queues_, message_queue);
145 if (iter != message_queues_.end()) {
146 message_queues_.erase(iter);
147 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100148#if RTC_DCHECK_IS_ON
149 RemoveFromSendGraph(message_queue);
150#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100151 }
152}
153
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100154#if RTC_DCHECK_IS_ON
155void ThreadManager::RemoveFromSendGraph(Thread* thread) {
156 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
157 if (it->first == thread) {
158 it = send_graph_.erase(it);
159 } else {
160 it->second.erase(thread);
161 ++it;
162 }
163 }
164}
165
166void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
167 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200168 RTC_DCHECK(source);
169 RTC_DCHECK(target);
170
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100171 CritScope cs(&crit_);
172 std::deque<Thread*> all_targets({target});
173 // We check the pre-existing who-sends-to-who graph for any path from target
174 // to source. This loop is guaranteed to terminate because per the send graph
175 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800176 for (size_t i = 0; i < all_targets.size(); i++) {
177 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100178 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
179 }
180 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
181 << " send loop between " << source->name() << " and " << target->name();
182
183 // We may now insert source -> target without creating a cycle, since there
184 // was no path from target to source per the prior CHECK.
185 send_graph_[source].insert(target);
186}
187#endif
188
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100189// static
190void ThreadManager::Clear(MessageHandler* handler) {
191 return Instance()->ClearInternal(handler);
192}
193void ThreadManager::ClearInternal(MessageHandler* handler) {
194 // Deleted objects may cause re-entrant calls to ClearInternal. This is
195 // allowed as the list of message queues does not change while queues are
196 // cleared.
197 MarkProcessingCritScope cs(&crit_, &processing_);
198 for (Thread* queue : message_queues_) {
199 queue->Clear(handler);
200 }
201}
202
203// static
204void ThreadManager::ProcessAllMessageQueuesForTesting() {
205 return Instance()->ProcessAllMessageQueuesInternal();
206}
207
208void ThreadManager::ProcessAllMessageQueuesInternal() {
209 // This works by posting a delayed message at the current time and waiting
210 // for it to be dispatched on all queues, which will ensure that all messages
211 // that came before it were also dispatched.
212 volatile int queues_not_done = 0;
213
214 // This class is used so that whether the posted message is processed, or the
215 // message queue is simply cleared, queues_not_done gets decremented.
216 class ScopedIncrement : public MessageData {
217 public:
218 ScopedIncrement(volatile int* value) : value_(value) {
219 AtomicOps::Increment(value_);
220 }
221 ~ScopedIncrement() override { AtomicOps::Decrement(value_); }
222
223 private:
224 volatile int* value_;
225 };
226
227 {
228 MarkProcessingCritScope cs(&crit_, &processing_);
229 for (Thread* queue : message_queues_) {
230 if (!queue->IsProcessingMessagesForTesting()) {
231 // If the queue is not processing messages, it can
232 // be ignored. If we tried to post a message to it, it would be dropped
233 // or ignored.
234 continue;
235 }
236 queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
237 new ScopedIncrement(&queues_not_done));
238 }
239 }
240
241 rtc::Thread* current = rtc::Thread::Current();
242 // Note: One of the message queues may have been on this thread, which is
243 // why we can't synchronously wait for queues_not_done to go to 0; we need
244 // to process messages as well.
245 while (AtomicOps::AcquireLoad(&queues_not_done) > 0) {
246 if (current) {
247 current->ProcessMessages(0);
248 }
249 }
250}
251
252// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000253Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700254 ThreadManager* manager = ThreadManager::Instance();
255 Thread* thread = manager->CurrentThread();
256
Niels Moller9d1840c2019-05-21 07:26:37 +0000257#ifndef NO_MAIN_THREAD_WRAPPING
258 // Only autowrap the thread which instantiated the ThreadManager.
259 if (!thread && manager->IsMainThread()) {
260 thread = new Thread(SocketServer::CreateDefault());
261 thread->WrapCurrentWithThreadManager(manager, true);
262 }
263#endif
264
nisse7866cfe2017-04-26 01:45:31 -0700265 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000266}
267
268#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +0000269ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200270#if defined(WEBRTC_MAC)
271 InitCocoaMultiThreading();
272#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800273 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000274}
275
Yves Gerey665174f2018-06-19 15:03:05 +0200276Thread* ThreadManager::CurrentThread() {
277 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278}
279
Sebastian Jansson178a6852020-01-14 11:12:26 +0100280void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281 pthread_setspecific(key_, thread);
282}
283#endif
284
285#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000286ThreadManager::ThreadManager()
287 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200288
289Thread* ThreadManager::CurrentThread() {
290 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291}
292
Sebastian Jansson178a6852020-01-14 11:12:26 +0100293void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000294 TlsSetValue(key_, thread);
295}
296#endif
297
Sebastian Jansson178a6852020-01-14 11:12:26 +0100298void ThreadManager::SetCurrentThread(Thread* thread) {
299#if RTC_DLOG_IS_ON
300 if (CurrentThread() && thread) {
301 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
302 }
303#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200304
305 if (thread) {
306 thread->EnsureIsCurrentTaskQueue();
307 } else {
308 Thread* current = CurrentThread();
309 if (current) {
310 // The current thread is being cleared, e.g. as a result of
311 // UnwrapCurrent() being called or when a thread is being stopped
312 // (see PreRun()). This signals that the Thread instance is being detached
313 // from the thread, which also means that TaskQueue::Current() must not
314 // return a pointer to the Thread instance.
315 current->ClearCurrentTaskQueue();
316 }
317 }
318
Sebastian Jansson178a6852020-01-14 11:12:26 +0100319 SetCurrentThreadInternal(thread);
320}
321
322void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
323 SetCurrentThreadInternal(thread);
324}
325
Yves Gerey665174f2018-06-19 15:03:05 +0200326Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000327 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800328 if (nullptr == result) {
tommie7251592017-07-14 14:44:46 -0700329 result = new Thread(SocketServer::CreateDefault());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000330 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000331 }
332 return result;
333}
334
335void ThreadManager::UnwrapCurrentThread() {
336 Thread* t = CurrentThread();
337 if (t && !(t->IsOwned())) {
338 t->UnwrapCurrent();
339 delete t;
340 }
341}
342
Niels Moller9d1840c2019-05-21 07:26:37 +0000343bool ThreadManager::IsMainThread() {
344 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
345}
346
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000347Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200348 : thread_(Thread::Current()),
349 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000350
351Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800352 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000353 thread_->SetAllowBlockingCalls(previous_state_);
354}
355
Taylor Brandstetter08672602018-03-02 15:20:33 -0800356Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700357
358Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800359 : Thread(std::move(ss), /*do_init=*/true) {}
360
361Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100362 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100363 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100364 fInitialized_(false),
365 fDestroyed_(false),
366 stop_(0),
367 ss_(ss) {
368 RTC_DCHECK(ss);
369 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800370 SetName("Thread", this); // default name
371 if (do_init) {
372 DoInit();
373 }
374}
375
376Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100377 : Thread(ss.get(), do_init) {
378 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000379}
380
381Thread::~Thread() {
382 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800383 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000384}
385
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100386void Thread::DoInit() {
387 if (fInitialized_) {
388 return;
389 }
390
391 fInitialized_ = true;
392 ThreadManager::Add(this);
393}
394
395void Thread::DoDestroy() {
396 if (fDestroyed_) {
397 return;
398 }
399
400 fDestroyed_ = true;
401 // The signal is done from here to ensure
402 // that it always gets called when the queue
403 // is going away.
404 SignalQueueDestroyed();
405 ThreadManager::Remove(this);
406 ClearInternal(nullptr, MQID_ANY, nullptr);
407
408 if (ss_) {
409 ss_->SetMessageQueue(nullptr);
410 }
411}
412
413SocketServer* Thread::socketserver() {
414 return ss_;
415}
416
417void Thread::WakeUpSocketServer() {
418 ss_->WakeUp();
419}
420
421void Thread::Quit() {
422 AtomicOps::ReleaseStore(&stop_, 1);
423 WakeUpSocketServer();
424}
425
426bool Thread::IsQuitting() {
427 return AtomicOps::AcquireLoad(&stop_) != 0;
428}
429
430void Thread::Restart() {
431 AtomicOps::ReleaseStore(&stop_, 0);
432}
433
434bool Thread::Peek(Message* pmsg, int cmsWait) {
435 if (fPeekKeep_) {
436 *pmsg = msgPeek_;
437 return true;
438 }
439 if (!Get(pmsg, cmsWait))
440 return false;
441 msgPeek_ = *pmsg;
442 fPeekKeep_ = true;
443 return true;
444}
445
446bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
447 // Return and clear peek if present
448 // Always return the peek if it exists so there is Peek/Get symmetry
449
450 if (fPeekKeep_) {
451 *pmsg = msgPeek_;
452 fPeekKeep_ = false;
453 return true;
454 }
455
456 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
457
458 int64_t cmsTotal = cmsWait;
459 int64_t cmsElapsed = 0;
460 int64_t msStart = TimeMillis();
461 int64_t msCurrent = msStart;
462 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100463 // Check for posted events
464 int64_t cmsDelayNext = kForever;
465 bool first_pass = true;
466 while (true) {
467 // All queue operations need to be locked, but nothing else in this loop
468 // (specifically handling disposed message) can happen inside the crit.
469 // Otherwise, disposed MessageHandlers will cause deadlocks.
470 {
471 CritScope cs(&crit_);
472 // On the first pass, check for delayed messages that have been
473 // triggered and calculate the next trigger time.
474 if (first_pass) {
475 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100476 while (!delayed_messages_.empty()) {
477 if (msCurrent < delayed_messages_.top().run_time_ms_) {
478 cmsDelayNext =
479 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100480 break;
481 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100482 messages_.push_back(delayed_messages_.top().msg_);
483 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100484 }
485 }
486 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100487 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100488 break;
489 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100490 *pmsg = messages_.front();
491 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100492 }
493 } // crit_ is released here.
494
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100495 // If this was a dispose message, delete it and skip it.
496 if (MQID_DISPOSE == pmsg->message_id) {
497 RTC_DCHECK(nullptr == pmsg->phandler);
498 delete pmsg->pdata;
499 *pmsg = Message();
500 continue;
501 }
502 return true;
503 }
504
505 if (IsQuitting())
506 break;
507
508 // Which is shorter, the delay wait or the asked wait?
509
510 int64_t cmsNext;
511 if (cmsWait == kForever) {
512 cmsNext = cmsDelayNext;
513 } else {
514 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
515 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
516 cmsNext = cmsDelayNext;
517 }
518
519 {
520 // Wait and multiplex in the meantime
521 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
522 return false;
523 }
524
525 // If the specified timeout expired, return
526
527 msCurrent = TimeMillis();
528 cmsElapsed = TimeDiff(msCurrent, msStart);
529 if (cmsWait != kForever) {
530 if (cmsElapsed >= cmsWait)
531 return false;
532 }
533 }
534 return false;
535}
536
537void Thread::Post(const Location& posted_from,
538 MessageHandler* phandler,
539 uint32_t id,
540 MessageData* pdata,
541 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100542 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100543 if (IsQuitting()) {
544 delete pdata;
545 return;
546 }
547
548 // Keep thread safe
549 // Add the message to the end of the queue
550 // Signal for the multiplexer to return
551
552 {
553 CritScope cs(&crit_);
554 Message msg;
555 msg.posted_from = posted_from;
556 msg.phandler = phandler;
557 msg.message_id = id;
558 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100559 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100560 }
561 WakeUpSocketServer();
562}
563
564void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100565 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100566 MessageHandler* phandler,
567 uint32_t id,
568 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100569 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100570 pdata);
571}
572
573void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100574 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100575 MessageHandler* phandler,
576 uint32_t id,
577 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100578 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100579 pdata);
580}
581
582void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100583 int64_t delay_ms,
584 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100585 MessageHandler* phandler,
586 uint32_t id,
587 MessageData* pdata) {
588 if (IsQuitting()) {
589 delete pdata;
590 return;
591 }
592
593 // Keep thread safe
594 // Add to the priority queue. Gets sorted soonest first.
595 // Signal for the multiplexer to return.
596
597 {
598 CritScope cs(&crit_);
599 Message msg;
600 msg.posted_from = posted_from;
601 msg.phandler = phandler;
602 msg.message_id = id;
603 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100604 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
605 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100606 // If this message queue processes 1 message every millisecond for 50 days,
607 // we will wrap this number. Even then, only messages with identical times
608 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100609 ++delayed_next_num_;
610 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100611 }
612 WakeUpSocketServer();
613}
614
615int Thread::GetDelay() {
616 CritScope cs(&crit_);
617
Sebastian Jansson61380c02020-01-17 14:46:08 +0100618 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100619 return 0;
620
Sebastian Jansson61380c02020-01-17 14:46:08 +0100621 if (!delayed_messages_.empty()) {
622 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100623 if (delay < 0)
624 delay = 0;
625 return delay;
626 }
627
628 return kForever;
629}
630
631void Thread::ClearInternal(MessageHandler* phandler,
632 uint32_t id,
633 MessageList* removed) {
634 // Remove messages with phandler
635
636 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
637 if (removed) {
638 removed->push_back(msgPeek_);
639 } else {
640 delete msgPeek_.pdata;
641 }
642 fPeekKeep_ = false;
643 }
644
645 // Remove from ordered message queue
646
Sebastian Jansson61380c02020-01-17 14:46:08 +0100647 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100648 if (it->Match(phandler, id)) {
649 if (removed) {
650 removed->push_back(*it);
651 } else {
652 delete it->pdata;
653 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100654 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100655 } else {
656 ++it;
657 }
658 }
659
660 // Remove from priority queue. Not directly iterable, so use this approach
661
Sebastian Jansson61380c02020-01-17 14:46:08 +0100662 auto new_end = delayed_messages_.container().begin();
663 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100664 if (it->msg_.Match(phandler, id)) {
665 if (removed) {
666 removed->push_back(it->msg_);
667 } else {
668 delete it->msg_.pdata;
669 }
670 } else {
671 *new_end++ = *it;
672 }
673 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100674 delayed_messages_.container().erase(new_end,
675 delayed_messages_.container().end());
676 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100677}
678
679void Thread::Dispatch(Message* pmsg) {
680 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
681 pmsg->posted_from.file_name(), "src_func",
682 pmsg->posted_from.function_name());
683 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);
687 if (diff >= kSlowDispatchLoggingThreshold) {
688 RTC_LOG(LS_INFO) << "Message took " << diff
689 << "ms to dispatch. Posted from: "
690 << pmsg->posted_from.ToString();
691 }
692}
693
nisse7866cfe2017-04-26 01:45:31 -0700694bool Thread::IsCurrent() const {
695 return ThreadManager::Instance()->CurrentThread() == this;
696}
697
danilchapbebf54c2016-04-28 01:32:48 -0700698std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
699 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
700}
701
702std::unique_ptr<Thread> Thread::Create() {
703 return std::unique_ptr<Thread>(
704 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
705}
706
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000707bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000708 AssertBlockingIsAllowedOnCurrentThread();
709
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000710#if defined(WEBRTC_WIN)
711 ::Sleep(milliseconds);
712 return true;
713#else
714 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
715 // so we use nanosleep() even though it has greater precision than necessary.
716 struct timespec ts;
717 ts.tv_sec = milliseconds / 1000;
718 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800719 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000720 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100721 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000722 return false;
723 }
724 return true;
725#endif
726}
727
728bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100729 RTC_DCHECK(!IsRunning());
730
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000731 name_ = name;
732 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200733 // The %p specifier typically produce at most 16 hex digits, possibly with a
734 // 0x prefix. But format is implementation defined, so add some margin.
735 char buf[30];
736 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000737 name_ += buf;
738 }
739 return true;
740}
741
Niels Möllerd2e50132019-06-11 09:24:14 +0200742bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100743 RTC_DCHECK(!IsRunning());
744
745 if (IsRunning())
746 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000747
André Susano Pinto02a57972016-07-22 13:30:05 +0200748 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000749
750 // Make sure that ThreadManager is created on the main thread before
751 // we start a new thread.
752 ThreadManager::Instance();
753
Tommi51492422017-12-04 15:18:23 +0100754 owned_ = true;
755
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000756#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200757 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100758 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000759 return false;
760 }
761#elif defined(WEBRTC_POSIX)
762 pthread_attr_t attr;
763 pthread_attr_init(&attr);
764
Niels Möllerd2e50132019-06-11 09:24:14 +0200765 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000766 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100767 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100768 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000769 return false;
770 }
Tommi51492422017-12-04 15:18:23 +0100771 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000772#endif
773 return true;
774}
775
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000776bool Thread::WrapCurrent() {
777 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
778}
779
780void Thread::UnwrapCurrent() {
781 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800782 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000783#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800784 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000785 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100786 RTC_LOG_GLE(LS_ERROR)
787 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000788 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800789 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100790 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000791 }
Tommi51492422017-12-04 15:18:23 +0100792#elif defined(WEBRTC_POSIX)
793 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000794#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000795}
796
797void Thread::SafeWrapCurrent() {
798 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
799}
800
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000801void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100802 if (!IsRunning())
803 return;
804
805 RTC_DCHECK(!IsCurrent());
806 if (Current() && !Current()->blocking_calls_allowed_) {
807 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100808 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100809 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000810
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000811#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100812 RTC_DCHECK(thread_ != nullptr);
813 WaitForSingleObject(thread_, INFINITE);
814 CloseHandle(thread_);
815 thread_ = nullptr;
816 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000817#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100818 pthread_join(thread_, nullptr);
819 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000820#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000821}
822
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000823bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800824 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000825 bool previous = blocking_calls_allowed_;
826 blocking_calls_allowed_ = allow;
827 return previous;
828}
829
830// static
831void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700832#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000833 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800834 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000835#endif
836}
837
deadbeefdc20e262017-01-31 15:10:44 -0800838// static
839#if defined(WEBRTC_WIN)
840DWORD WINAPI Thread::PreRun(LPVOID pv) {
841#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000842void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800843#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200844 Thread* thread = static_cast<Thread*>(pv);
845 ThreadManager::Instance()->SetCurrentThread(thread);
846 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200847#if defined(WEBRTC_MAC)
848 ScopedAutoReleasePool pool;
849#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200850 thread->Run();
851
Tommi51492422017-12-04 15:18:23 +0100852 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800853#ifdef WEBRTC_WIN
854 return 0;
855#else
856 return nullptr;
857#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200858} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000859
860void Thread::Run() {
861 ProcessMessages(kForever);
862}
863
864bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100865 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000866 return owned_;
867}
868
869void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100870 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000871 Join();
872}
873
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700874void Thread::Send(const Location& posted_from,
875 MessageHandler* phandler,
876 uint32_t id,
877 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100878 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200879 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000880 return;
881
882 // Sent messages are sent to the MessageHandler directly, in the context
883 // of "thread", like Win32 SendMessage. If in the right context,
884 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000885 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700886 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000887 msg.phandler = phandler;
888 msg.message_id = id;
889 msg.pdata = pdata;
890 if (IsCurrent()) {
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100891 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000892 return;
893 }
894
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000895 AssertBlockingIsAllowedOnCurrentThread();
896
Yves Gerey665174f2018-06-19 15:03:05 +0200897 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200898
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100899#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200900 if (current_thread) {
901 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
902 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
903 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000904 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200905#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000906
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200907 // Perhaps down the line we can get rid of this workaround and always require
908 // current_thread to be valid when Send() is called.
909 std::unique_ptr<rtc::Event> done_event;
910 if (!current_thread)
911 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000912
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200913 bool ready = false;
914 PostTask(webrtc::ToQueuedTask(
915 [&msg]() mutable { msg.phandler->OnMessage(&msg); },
916 [this, &ready, current_thread, done = done_event.get()] {
917 if (current_thread) {
918 CritScope cs(&crit_);
919 ready = true;
920 current_thread->socketserver()->WakeUp();
921 } else {
922 done->Set();
923 }
924 }));
925
926 if (current_thread) {
927 bool waited = false;
928 crit_.Enter();
929 while (!ready) {
930 crit_.Leave();
931 current_thread->socketserver()->Wait(kForever, false);
932 waited = true;
933 crit_.Enter();
934 }
935 crit_.Leave();
936
937 // Our Wait loop above may have consumed some WakeUp events for this
938 // Thread, that weren't relevant to this Send. Losing these WakeUps can
939 // cause problems for some SocketServers.
940 //
941 // Concrete example:
942 // Win32SocketServer on thread A calls Send on thread B. While processing
943 // the message, thread B Posts a message to A. We consume the wakeup for
944 // that Post while waiting for the Send to complete, which means that when
945 // we exit this loop, we need to issue another WakeUp, or else the Posted
946 // message won't be processed in a timely manner.
947
948 if (waited) {
949 current_thread->socketserver()->WakeUp();
950 }
951 } else {
952 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000953 }
954}
955
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700956void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100957 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800958 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
959 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100960
961 class FunctorMessageHandler : public MessageHandler {
962 public:
963 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200964 : MessageHandler(false), functor_(functor) {}
Danil Chapovalov89313452019-11-29 12:56:43 +0100965 void OnMessage(Message* msg) override { functor_(); }
966
967 private:
968 rtc::FunctionView<void()> functor_;
969 } handler(functor);
970
971 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000972}
973
Tommi6866dc72020-05-15 10:11:56 +0200974// Called by the ThreadManager when being set as the current thread.
975void Thread::EnsureIsCurrentTaskQueue() {
976 task_queue_registration_ =
977 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
978}
979
980// Called by the ThreadManager when being set as the current thread.
981void Thread::ClearCurrentTaskQueue() {
982 task_queue_registration_.reset();
983}
984
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100985void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
986 RTC_DCHECK(msg);
987 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
988 std::unique_ptr<webrtc::QueuedTask> task = std::move(data->data());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100989 // Thread expects handler to own Message::pdata when OnMessage is called
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100990 // Since MessageData is no longer needed, delete it.
991 delete data;
992
993 // QueuedTask interface uses Run return value to communicate who owns the
994 // task. false means QueuedTask took the ownership.
995 if (!task->Run())
996 task.release();
997}
998
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200999void Thread::AllowInvokesToThread(Thread* thread) {
1000#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1001 if (!IsCurrent()) {
1002 PostTask(webrtc::ToQueuedTask(
1003 [thread, this]() { AllowInvokesToThread(thread); }));
1004 return;
1005 }
1006 RTC_DCHECK_RUN_ON(this);
1007 allowed_threads_.push_back(thread);
1008 invoke_policy_enabled_ = true;
1009#endif
1010}
1011
1012void Thread::DisallowAllInvokes() {
1013#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1014 if (!IsCurrent()) {
1015 PostTask(webrtc::ToQueuedTask([this]() { DisallowAllInvokes(); }));
1016 return;
1017 }
1018 RTC_DCHECK_RUN_ON(this);
1019 allowed_threads_.clear();
1020 invoke_policy_enabled_ = true;
1021#endif
1022}
1023
1024// Returns true if no policies added or if there is at least one policy
1025// that permits invocation to |target| thread.
1026bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
1027#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1028 RTC_DCHECK_RUN_ON(this);
1029 if (!invoke_policy_enabled_) {
1030 return true;
1031 }
1032 for (const auto* thread : allowed_threads_) {
1033 if (thread == target) {
1034 return true;
1035 }
1036 }
1037 return false;
1038#else
1039 return true;
1040#endif
1041}
1042
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001043void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
1044 // Though Post takes MessageData by raw pointer (last parameter), it still
1045 // takes it with ownership.
1046 Post(RTC_FROM_HERE, &queued_task_handler_,
1047 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1048}
1049
1050void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
1051 uint32_t milliseconds) {
1052 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1053 // it still takes it with ownership.
1054 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
1055 /*id=*/0,
1056 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1057}
1058
1059void Thread::Delete() {
1060 Stop();
1061 delete this;
1062}
1063
Niels Möller8909a632018-09-06 08:42:44 +02001064bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001065 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001066}
1067
Peter Boström0c4e06b2015-10-07 12:23:21 +02001068void Thread::Clear(MessageHandler* phandler,
1069 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001070 MessageList* removed) {
1071 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001072 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001073}
1074
1075bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001076 // Using ProcessMessages with a custom clock for testing and a time greater
1077 // than 0 doesn't work, since it's not guaranteed to advance the custom
1078 // clock's time, and may get stuck in an infinite loop.
1079 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1080 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001081 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001082 int cmsNext = cmsLoop;
1083
1084 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001085#if defined(WEBRTC_MAC)
1086 ScopedAutoReleasePool pool;
1087#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001088 Message msg;
1089 if (!Get(&msg, cmsNext))
1090 return !IsQuitting();
1091 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001092
kthelgasonde6adbe2017-02-22 00:42:11 -08001093 if (cmsLoop != kForever) {
1094 cmsNext = static_cast<int>(TimeUntil(msEnd));
1095 if (cmsNext < 0)
1096 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001097 }
1098 }
1099}
1100
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001101bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1102 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001103 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001104
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001105#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001106 if (need_synchronize_access) {
1107 // We explicitly ask for no rights other than synchronization.
1108 // This gives us the best chance of succeeding.
1109 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1110 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001111 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001112 return false;
1113 }
1114 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001115 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001116#elif defined(WEBRTC_POSIX)
1117 thread_ = pthread_self();
1118#endif
1119 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001120 thread_manager->SetCurrentThread(this);
1121 return true;
1122}
1123
Tommi51492422017-12-04 15:18:23 +01001124bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001125#if defined(WEBRTC_WIN)
1126 return thread_ != nullptr;
1127#elif defined(WEBRTC_POSIX)
1128 return thread_ != 0;
1129#endif
1130}
1131
Steve Antonbcc1a762019-12-11 11:21:53 -08001132// static
1133MessageHandler* Thread::GetPostTaskMessageHandler() {
1134 // Allocate at first call, never deallocate.
1135 static MessageHandler* handler = new MessageHandlerWithTask;
1136 return handler;
1137}
1138
Taylor Brandstetter08672602018-03-02 15:20:33 -08001139AutoThread::AutoThread()
1140 : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001141 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001142 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001143 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1144 // post a message to a queue that no running thread is serving.
1145 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001146 ThreadManager::Instance()->SetCurrentThread(this);
1147 }
1148}
1149
1150AutoThread::~AutoThread() {
1151 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001152 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001153 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001154 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001155 }
1156}
1157
nisse7eaa4ea2017-05-08 05:25:41 -07001158AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001159 : Thread(ss, /*do_init=*/false) {
1160 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001161 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001162 // Temporarily set the current thread to nullptr so that we can keep checks
1163 // around that catch unintentional pointer overwrites.
1164 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001165 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1166 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001167 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001168 }
1169}
1170
1171AutoSocketServerThread::~AutoSocketServerThread() {
1172 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
1173 // Some tests post destroy messages to this thread. To avoid memory
1174 // leaks, we have to process those messages. In particular
1175 // P2PTransportChannelPingTest, relying on the message posted in
1176 // cricket::Connection::Destroy.
1177 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -07001178 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001179 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001180 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1181 // its contents rely on this thread still being set as the current thread.
1182 Stop();
1183 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001184 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001185 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1186 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001187 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001188 }
1189}
1190
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001191} // namespace rtc