blob: 5e48e4b857c99ee69370a180c8741956637e8adf [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"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/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"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010037#include "rtc_base/task_utils/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020041#if defined(WEBRTC_MAC)
42#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020043
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020044/*
45 * These are forward-declarations for methods that are part of the
46 * ObjC runtime. They are declared in the private header objc-internal.h.
47 * These calls are what clang inserts when using @autoreleasepool in ObjC,
48 * but here they are used directly in order to keep this file C++.
49 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
50 */
51extern "C" {
52void* objc_autoreleasePoolPush(void);
53void objc_autoreleasePoolPop(void* pool);
54}
55
56namespace {
57class ScopedAutoReleasePool {
58 public:
59 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
60 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
61
62 private:
63 void* const pool_;
64};
65} // namespace
66#endif
67
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000068namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080069namespace {
70
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010071const int kSlowDispatchLoggingThreshold = 50; // 50 ms
72
Steve Antonbcc1a762019-12-11 11:21:53 -080073class MessageHandlerWithTask final : public MessageHandler {
74 public:
75 MessageHandlerWithTask() = default;
76
77 void OnMessage(Message* msg) override {
78 static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
79 delete msg->pdata;
80 }
81
82 private:
83 ~MessageHandlerWithTask() override {}
84
85 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
86};
87
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010088class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
89 public:
90 MarkProcessingCritScope(const CriticalSection* cs, size_t* processing)
91 RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
92 : cs_(cs), processing_(processing) {
93 cs_->Enter();
94 *processing_ += 1;
95 }
96
97 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
98 *processing_ -= 1;
99 cs_->Leave();
100 }
101
102 private:
103 const CriticalSection* const cs_;
104 size_t* processing_;
105
106 RTC_DISALLOW_COPY_AND_ASSIGN(MarkProcessingCritScope);
107};
108
Steve Antonbcc1a762019-12-11 11:21:53 -0800109} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000110
111ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200112 static ThreadManager* const thread_manager = new ThreadManager();
113 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000114}
115
nisse7866cfe2017-04-26 01:45:31 -0700116ThreadManager::~ThreadManager() {
117 // By above RTC_DEFINE_STATIC_LOCAL.
118 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
119}
120
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100122void ThreadManager::Add(Thread* message_queue) {
123 return Instance()->AddInternal(message_queue);
124}
125void ThreadManager::AddInternal(Thread* message_queue) {
126 CritScope cs(&crit_);
127 // Prevent changes while the list of message queues is processed.
128 RTC_DCHECK_EQ(processing_, 0);
129 message_queues_.push_back(message_queue);
130}
131
132// static
133void ThreadManager::Remove(Thread* message_queue) {
134 return Instance()->RemoveInternal(message_queue);
135}
136void ThreadManager::RemoveInternal(Thread* message_queue) {
137 {
138 CritScope cs(&crit_);
139 // Prevent changes while the list of message queues is processed.
140 RTC_DCHECK_EQ(processing_, 0);
141 std::vector<Thread*>::iterator iter;
142 iter = absl::c_find(message_queues_, message_queue);
143 if (iter != message_queues_.end()) {
144 message_queues_.erase(iter);
145 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100146#if RTC_DCHECK_IS_ON
147 RemoveFromSendGraph(message_queue);
148#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100149 }
150}
151
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100152#if RTC_DCHECK_IS_ON
153void ThreadManager::RemoveFromSendGraph(Thread* thread) {
154 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
155 if (it->first == thread) {
156 it = send_graph_.erase(it);
157 } else {
158 it->second.erase(thread);
159 ++it;
160 }
161 }
162}
163
164void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
165 Thread* target) {
166 CritScope cs(&crit_);
167 std::deque<Thread*> all_targets({target});
168 // We check the pre-existing who-sends-to-who graph for any path from target
169 // to source. This loop is guaranteed to terminate because per the send graph
170 // invariant, there are no cycles in the graph.
171 for (auto it = all_targets.begin(); it != all_targets.end(); ++it) {
172 const auto& targets = send_graph_[*it];
173 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
174 }
175 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
176 << " send loop between " << source->name() << " and " << target->name();
177
178 // We may now insert source -> target without creating a cycle, since there
179 // was no path from target to source per the prior CHECK.
180 send_graph_[source].insert(target);
181}
182#endif
183
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100184// static
185void ThreadManager::Clear(MessageHandler* handler) {
186 return Instance()->ClearInternal(handler);
187}
188void ThreadManager::ClearInternal(MessageHandler* handler) {
189 // Deleted objects may cause re-entrant calls to ClearInternal. This is
190 // allowed as the list of message queues does not change while queues are
191 // cleared.
192 MarkProcessingCritScope cs(&crit_, &processing_);
193 for (Thread* queue : message_queues_) {
194 queue->Clear(handler);
195 }
196}
197
198// static
199void ThreadManager::ProcessAllMessageQueuesForTesting() {
200 return Instance()->ProcessAllMessageQueuesInternal();
201}
202
203void ThreadManager::ProcessAllMessageQueuesInternal() {
204 // This works by posting a delayed message at the current time and waiting
205 // for it to be dispatched on all queues, which will ensure that all messages
206 // that came before it were also dispatched.
207 volatile int queues_not_done = 0;
208
209 // This class is used so that whether the posted message is processed, or the
210 // message queue is simply cleared, queues_not_done gets decremented.
211 class ScopedIncrement : public MessageData {
212 public:
213 ScopedIncrement(volatile int* value) : value_(value) {
214 AtomicOps::Increment(value_);
215 }
216 ~ScopedIncrement() override { AtomicOps::Decrement(value_); }
217
218 private:
219 volatile int* value_;
220 };
221
222 {
223 MarkProcessingCritScope cs(&crit_, &processing_);
224 for (Thread* queue : message_queues_) {
225 if (!queue->IsProcessingMessagesForTesting()) {
226 // If the queue is not processing messages, it can
227 // be ignored. If we tried to post a message to it, it would be dropped
228 // or ignored.
229 continue;
230 }
231 queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
232 new ScopedIncrement(&queues_not_done));
233 }
234 }
235
236 rtc::Thread* current = rtc::Thread::Current();
237 // Note: One of the message queues may have been on this thread, which is
238 // why we can't synchronously wait for queues_not_done to go to 0; we need
239 // to process messages as well.
240 while (AtomicOps::AcquireLoad(&queues_not_done) > 0) {
241 if (current) {
242 current->ProcessMessages(0);
243 }
244 }
245}
246
247// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000248Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700249 ThreadManager* manager = ThreadManager::Instance();
250 Thread* thread = manager->CurrentThread();
251
Niels Moller9d1840c2019-05-21 07:26:37 +0000252#ifndef NO_MAIN_THREAD_WRAPPING
253 // Only autowrap the thread which instantiated the ThreadManager.
254 if (!thread && manager->IsMainThread()) {
255 thread = new Thread(SocketServer::CreateDefault());
256 thread->WrapCurrentWithThreadManager(manager, true);
257 }
258#endif
259
nisse7866cfe2017-04-26 01:45:31 -0700260 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261}
262
263#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +0000264ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200265#if defined(WEBRTC_MAC)
266 InitCocoaMultiThreading();
267#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800268 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269}
270
Yves Gerey665174f2018-06-19 15:03:05 +0200271Thread* ThreadManager::CurrentThread() {
272 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273}
274
Sebastian Jansson178a6852020-01-14 11:12:26 +0100275void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276 pthread_setspecific(key_, thread);
277}
278#endif
279
280#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000281ThreadManager::ThreadManager()
282 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200283
284Thread* ThreadManager::CurrentThread() {
285 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286}
287
Sebastian Jansson178a6852020-01-14 11:12:26 +0100288void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000289 TlsSetValue(key_, thread);
290}
291#endif
292
Sebastian Jansson178a6852020-01-14 11:12:26 +0100293void ThreadManager::SetCurrentThread(Thread* thread) {
294#if RTC_DLOG_IS_ON
295 if (CurrentThread() && thread) {
296 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
297 }
298#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200299
300 if (thread) {
301 thread->EnsureIsCurrentTaskQueue();
302 } else {
303 Thread* current = CurrentThread();
304 if (current) {
305 // The current thread is being cleared, e.g. as a result of
306 // UnwrapCurrent() being called or when a thread is being stopped
307 // (see PreRun()). This signals that the Thread instance is being detached
308 // from the thread, which also means that TaskQueue::Current() must not
309 // return a pointer to the Thread instance.
310 current->ClearCurrentTaskQueue();
311 }
312 }
313
Sebastian Jansson178a6852020-01-14 11:12:26 +0100314 SetCurrentThreadInternal(thread);
315}
316
317void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
318 SetCurrentThreadInternal(thread);
319}
320
Yves Gerey665174f2018-06-19 15:03:05 +0200321Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000322 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800323 if (nullptr == result) {
tommie7251592017-07-14 14:44:46 -0700324 result = new Thread(SocketServer::CreateDefault());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000325 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326 }
327 return result;
328}
329
330void ThreadManager::UnwrapCurrentThread() {
331 Thread* t = CurrentThread();
332 if (t && !(t->IsOwned())) {
333 t->UnwrapCurrent();
334 delete t;
335 }
336}
337
Niels Moller9d1840c2019-05-21 07:26:37 +0000338bool ThreadManager::IsMainThread() {
339 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
340}
341
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000342Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200343 : thread_(Thread::Current()),
344 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000345
346Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800347 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000348 thread_->SetAllowBlockingCalls(previous_state_);
349}
350
Taylor Brandstetter08672602018-03-02 15:20:33 -0800351Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700352
353Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800354 : Thread(std::move(ss), /*do_init=*/true) {}
355
356Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100357 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100358 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100359 fInitialized_(false),
360 fDestroyed_(false),
361 stop_(0),
362 ss_(ss) {
363 RTC_DCHECK(ss);
364 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800365 SetName("Thread", this); // default name
366 if (do_init) {
367 DoInit();
368 }
369}
370
371Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100372 : Thread(ss.get(), do_init) {
373 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000374}
375
376Thread::~Thread() {
377 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800378 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000379}
380
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100381void Thread::DoInit() {
382 if (fInitialized_) {
383 return;
384 }
385
386 fInitialized_ = true;
387 ThreadManager::Add(this);
388}
389
390void Thread::DoDestroy() {
391 if (fDestroyed_) {
392 return;
393 }
394
395 fDestroyed_ = true;
396 // The signal is done from here to ensure
397 // that it always gets called when the queue
398 // is going away.
399 SignalQueueDestroyed();
400 ThreadManager::Remove(this);
401 ClearInternal(nullptr, MQID_ANY, nullptr);
402
403 if (ss_) {
404 ss_->SetMessageQueue(nullptr);
405 }
406}
407
408SocketServer* Thread::socketserver() {
409 return ss_;
410}
411
412void Thread::WakeUpSocketServer() {
413 ss_->WakeUp();
414}
415
416void Thread::Quit() {
417 AtomicOps::ReleaseStore(&stop_, 1);
418 WakeUpSocketServer();
419}
420
421bool Thread::IsQuitting() {
422 return AtomicOps::AcquireLoad(&stop_) != 0;
423}
424
425void Thread::Restart() {
426 AtomicOps::ReleaseStore(&stop_, 0);
427}
428
429bool Thread::Peek(Message* pmsg, int cmsWait) {
430 if (fPeekKeep_) {
431 *pmsg = msgPeek_;
432 return true;
433 }
434 if (!Get(pmsg, cmsWait))
435 return false;
436 msgPeek_ = *pmsg;
437 fPeekKeep_ = true;
438 return true;
439}
440
441bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
442 // Return and clear peek if present
443 // Always return the peek if it exists so there is Peek/Get symmetry
444
445 if (fPeekKeep_) {
446 *pmsg = msgPeek_;
447 fPeekKeep_ = false;
448 return true;
449 }
450
451 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
452
453 int64_t cmsTotal = cmsWait;
454 int64_t cmsElapsed = 0;
455 int64_t msStart = TimeMillis();
456 int64_t msCurrent = msStart;
457 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100458 // Check for posted events
459 int64_t cmsDelayNext = kForever;
460 bool first_pass = true;
461 while (true) {
462 // All queue operations need to be locked, but nothing else in this loop
463 // (specifically handling disposed message) can happen inside the crit.
464 // Otherwise, disposed MessageHandlers will cause deadlocks.
465 {
466 CritScope cs(&crit_);
467 // On the first pass, check for delayed messages that have been
468 // triggered and calculate the next trigger time.
469 if (first_pass) {
470 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100471 while (!delayed_messages_.empty()) {
472 if (msCurrent < delayed_messages_.top().run_time_ms_) {
473 cmsDelayNext =
474 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100475 break;
476 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100477 messages_.push_back(delayed_messages_.top().msg_);
478 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100479 }
480 }
481 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100482 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100483 break;
484 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100485 *pmsg = messages_.front();
486 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100487 }
488 } // crit_ is released here.
489
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100490 // If this was a dispose message, delete it and skip it.
491 if (MQID_DISPOSE == pmsg->message_id) {
492 RTC_DCHECK(nullptr == pmsg->phandler);
493 delete pmsg->pdata;
494 *pmsg = Message();
495 continue;
496 }
497 return true;
498 }
499
500 if (IsQuitting())
501 break;
502
503 // Which is shorter, the delay wait or the asked wait?
504
505 int64_t cmsNext;
506 if (cmsWait == kForever) {
507 cmsNext = cmsDelayNext;
508 } else {
509 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
510 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
511 cmsNext = cmsDelayNext;
512 }
513
514 {
515 // Wait and multiplex in the meantime
516 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
517 return false;
518 }
519
520 // If the specified timeout expired, return
521
522 msCurrent = TimeMillis();
523 cmsElapsed = TimeDiff(msCurrent, msStart);
524 if (cmsWait != kForever) {
525 if (cmsElapsed >= cmsWait)
526 return false;
527 }
528 }
529 return false;
530}
531
532void Thread::Post(const Location& posted_from,
533 MessageHandler* phandler,
534 uint32_t id,
535 MessageData* pdata,
536 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100537 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100538 if (IsQuitting()) {
539 delete pdata;
540 return;
541 }
542
543 // Keep thread safe
544 // Add the message to the end of the queue
545 // Signal for the multiplexer to return
546
547 {
548 CritScope cs(&crit_);
549 Message msg;
550 msg.posted_from = posted_from;
551 msg.phandler = phandler;
552 msg.message_id = id;
553 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100554 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100555 }
556 WakeUpSocketServer();
557}
558
559void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100560 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100561 MessageHandler* phandler,
562 uint32_t id,
563 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100564 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100565 pdata);
566}
567
568void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100569 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100570 MessageHandler* phandler,
571 uint32_t id,
572 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100573 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100574 pdata);
575}
576
577void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100578 int64_t delay_ms,
579 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100580 MessageHandler* phandler,
581 uint32_t id,
582 MessageData* pdata) {
583 if (IsQuitting()) {
584 delete pdata;
585 return;
586 }
587
588 // Keep thread safe
589 // Add to the priority queue. Gets sorted soonest first.
590 // Signal for the multiplexer to return.
591
592 {
593 CritScope cs(&crit_);
594 Message msg;
595 msg.posted_from = posted_from;
596 msg.phandler = phandler;
597 msg.message_id = id;
598 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100599 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
600 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100601 // If this message queue processes 1 message every millisecond for 50 days,
602 // we will wrap this number. Even then, only messages with identical times
603 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100604 ++delayed_next_num_;
605 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100606 }
607 WakeUpSocketServer();
608}
609
610int Thread::GetDelay() {
611 CritScope cs(&crit_);
612
Sebastian Jansson61380c02020-01-17 14:46:08 +0100613 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100614 return 0;
615
Sebastian Jansson61380c02020-01-17 14:46:08 +0100616 if (!delayed_messages_.empty()) {
617 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100618 if (delay < 0)
619 delay = 0;
620 return delay;
621 }
622
623 return kForever;
624}
625
626void Thread::ClearInternal(MessageHandler* phandler,
627 uint32_t id,
628 MessageList* removed) {
629 // Remove messages with phandler
630
631 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
632 if (removed) {
633 removed->push_back(msgPeek_);
634 } else {
635 delete msgPeek_.pdata;
636 }
637 fPeekKeep_ = false;
638 }
639
640 // Remove from ordered message queue
641
Sebastian Jansson61380c02020-01-17 14:46:08 +0100642 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100643 if (it->Match(phandler, id)) {
644 if (removed) {
645 removed->push_back(*it);
646 } else {
647 delete it->pdata;
648 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100649 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100650 } else {
651 ++it;
652 }
653 }
654
655 // Remove from priority queue. Not directly iterable, so use this approach
656
Sebastian Jansson61380c02020-01-17 14:46:08 +0100657 auto new_end = delayed_messages_.container().begin();
658 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100659 if (it->msg_.Match(phandler, id)) {
660 if (removed) {
661 removed->push_back(it->msg_);
662 } else {
663 delete it->msg_.pdata;
664 }
665 } else {
666 *new_end++ = *it;
667 }
668 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100669 delayed_messages_.container().erase(new_end,
670 delayed_messages_.container().end());
671 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100672}
673
674void Thread::Dispatch(Message* pmsg) {
675 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
676 pmsg->posted_from.file_name(), "src_func",
677 pmsg->posted_from.function_name());
678 int64_t start_time = TimeMillis();
679 pmsg->phandler->OnMessage(pmsg);
680 int64_t end_time = TimeMillis();
681 int64_t diff = TimeDiff(end_time, start_time);
682 if (diff >= kSlowDispatchLoggingThreshold) {
683 RTC_LOG(LS_INFO) << "Message took " << diff
684 << "ms to dispatch. Posted from: "
685 << pmsg->posted_from.ToString();
686 }
687}
688
nisse7866cfe2017-04-26 01:45:31 -0700689bool Thread::IsCurrent() const {
690 return ThreadManager::Instance()->CurrentThread() == this;
691}
692
danilchapbebf54c2016-04-28 01:32:48 -0700693std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
694 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
695}
696
697std::unique_ptr<Thread> Thread::Create() {
698 return std::unique_ptr<Thread>(
699 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
700}
701
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000702bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000703 AssertBlockingIsAllowedOnCurrentThread();
704
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000705#if defined(WEBRTC_WIN)
706 ::Sleep(milliseconds);
707 return true;
708#else
709 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
710 // so we use nanosleep() even though it has greater precision than necessary.
711 struct timespec ts;
712 ts.tv_sec = milliseconds / 1000;
713 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800714 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000715 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100716 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000717 return false;
718 }
719 return true;
720#endif
721}
722
723bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100724 RTC_DCHECK(!IsRunning());
725
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000726 name_ = name;
727 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200728 // The %p specifier typically produce at most 16 hex digits, possibly with a
729 // 0x prefix. But format is implementation defined, so add some margin.
730 char buf[30];
731 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000732 name_ += buf;
733 }
734 return true;
735}
736
Niels Möllerd2e50132019-06-11 09:24:14 +0200737bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100738 RTC_DCHECK(!IsRunning());
739
740 if (IsRunning())
741 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000742
André Susano Pinto02a57972016-07-22 13:30:05 +0200743 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000744
745 // Make sure that ThreadManager is created on the main thread before
746 // we start a new thread.
747 ThreadManager::Instance();
748
Tommi51492422017-12-04 15:18:23 +0100749 owned_ = true;
750
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000751#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200752 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100753 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000754 return false;
755 }
756#elif defined(WEBRTC_POSIX)
757 pthread_attr_t attr;
758 pthread_attr_init(&attr);
759
Niels Möllerd2e50132019-06-11 09:24:14 +0200760 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000761 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100762 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100763 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000764 return false;
765 }
Tommi51492422017-12-04 15:18:23 +0100766 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000767#endif
768 return true;
769}
770
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000771bool Thread::WrapCurrent() {
772 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
773}
774
775void Thread::UnwrapCurrent() {
776 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800777 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000778#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800779 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000780 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100781 RTC_LOG_GLE(LS_ERROR)
782 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000783 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800784 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100785 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000786 }
Tommi51492422017-12-04 15:18:23 +0100787#elif defined(WEBRTC_POSIX)
788 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000789#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000790}
791
792void Thread::SafeWrapCurrent() {
793 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
794}
795
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000796void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100797 if (!IsRunning())
798 return;
799
800 RTC_DCHECK(!IsCurrent());
801 if (Current() && !Current()->blocking_calls_allowed_) {
802 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100803 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100804 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000805
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000806#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100807 RTC_DCHECK(thread_ != nullptr);
808 WaitForSingleObject(thread_, INFINITE);
809 CloseHandle(thread_);
810 thread_ = nullptr;
811 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000812#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100813 pthread_join(thread_, nullptr);
814 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000815#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000816}
817
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000818bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800819 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000820 bool previous = blocking_calls_allowed_;
821 blocking_calls_allowed_ = allow;
822 return previous;
823}
824
825// static
826void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700827#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000828 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800829 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000830#endif
831}
832
deadbeefdc20e262017-01-31 15:10:44 -0800833// static
834#if defined(WEBRTC_WIN)
835DWORD WINAPI Thread::PreRun(LPVOID pv) {
836#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000837void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800838#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200839 Thread* thread = static_cast<Thread*>(pv);
840 ThreadManager::Instance()->SetCurrentThread(thread);
841 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200842#if defined(WEBRTC_MAC)
843 ScopedAutoReleasePool pool;
844#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200845 thread->Run();
846
Tommi51492422017-12-04 15:18:23 +0100847 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800848#ifdef WEBRTC_WIN
849 return 0;
850#else
851 return nullptr;
852#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200853} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000854
855void Thread::Run() {
856 ProcessMessages(kForever);
857}
858
859bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100860 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000861 return owned_;
862}
863
864void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100865 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000866 Join();
867}
868
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700869void Thread::Send(const Location& posted_from,
870 MessageHandler* phandler,
871 uint32_t id,
872 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100873 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200874 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000875 return;
876
877 // Sent messages are sent to the MessageHandler directly, in the context
878 // of "thread", like Win32 SendMessage. If in the right context,
879 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000880 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700881 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000882 msg.phandler = phandler;
883 msg.message_id = id;
884 msg.pdata = pdata;
885 if (IsCurrent()) {
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100886 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000887 return;
888 }
889
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000890 AssertBlockingIsAllowedOnCurrentThread();
891
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000892 AutoThread thread;
Yves Gerey665174f2018-06-19 15:03:05 +0200893 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800894 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100895#if RTC_DCHECK_IS_ON
896 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
897 this);
898#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000899 bool ready = false;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100900 PostTask(
901 webrtc::ToQueuedTask([msg]() mutable { msg.phandler->OnMessage(&msg); },
902 [this, &ready, current_thread] {
903 CritScope cs(&crit_);
904 ready = true;
905 current_thread->socketserver()->WakeUp();
906 }));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000907
908 bool waited = false;
909 crit_.Enter();
910 while (!ready) {
911 crit_.Leave();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000912 current_thread->socketserver()->Wait(kForever, false);
913 waited = true;
914 crit_.Enter();
915 }
916 crit_.Leave();
917
918 // Our Wait loop above may have consumed some WakeUp events for this
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100919 // Thread, that weren't relevant to this Send. Losing these WakeUps can
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000920 // cause problems for some SocketServers.
921 //
922 // Concrete example:
923 // Win32SocketServer on thread A calls Send on thread B. While processing the
924 // message, thread B Posts a message to A. We consume the wakeup for that
925 // Post while waiting for the Send to complete, which means that when we exit
926 // this loop, we need to issue another WakeUp, or else the Posted message
927 // won't be processed in a timely manner.
928
929 if (waited) {
930 current_thread->socketserver()->WakeUp();
931 }
932}
933
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700934void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100935 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800936 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
937 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100938
939 class FunctorMessageHandler : public MessageHandler {
940 public:
941 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
942 : functor_(functor) {}
943 void OnMessage(Message* msg) override { functor_(); }
944
945 private:
946 rtc::FunctionView<void()> functor_;
947 } handler(functor);
948
949 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000950}
951
Tommi6866dc72020-05-15 10:11:56 +0200952// Called by the ThreadManager when being set as the current thread.
953void Thread::EnsureIsCurrentTaskQueue() {
954 task_queue_registration_ =
955 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
956}
957
958// Called by the ThreadManager when being set as the current thread.
959void Thread::ClearCurrentTaskQueue() {
960 task_queue_registration_.reset();
961}
962
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100963void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
964 RTC_DCHECK(msg);
965 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
966 std::unique_ptr<webrtc::QueuedTask> task = std::move(data->data());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100967 // Thread expects handler to own Message::pdata when OnMessage is called
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100968 // Since MessageData is no longer needed, delete it.
969 delete data;
970
971 // QueuedTask interface uses Run return value to communicate who owns the
972 // task. false means QueuedTask took the ownership.
973 if (!task->Run())
974 task.release();
975}
976
977void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
978 // Though Post takes MessageData by raw pointer (last parameter), it still
979 // takes it with ownership.
980 Post(RTC_FROM_HERE, &queued_task_handler_,
981 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
982}
983
984void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
985 uint32_t milliseconds) {
986 // Though PostDelayed takes MessageData by raw pointer (last parameter),
987 // it still takes it with ownership.
988 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
989 /*id=*/0,
990 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
991}
992
993void Thread::Delete() {
994 Stop();
995 delete this;
996}
997
Niels Möller8909a632018-09-06 08:42:44 +0200998bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100999 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001000}
1001
Peter Boström0c4e06b2015-10-07 12:23:21 +02001002void Thread::Clear(MessageHandler* phandler,
1003 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001004 MessageList* removed) {
1005 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001006 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001007}
1008
1009bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001010 // Using ProcessMessages with a custom clock for testing and a time greater
1011 // than 0 doesn't work, since it's not guaranteed to advance the custom
1012 // clock's time, and may get stuck in an infinite loop.
1013 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1014 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001015 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001016 int cmsNext = cmsLoop;
1017
1018 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001019#if defined(WEBRTC_MAC)
1020 ScopedAutoReleasePool pool;
1021#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001022 Message msg;
1023 if (!Get(&msg, cmsNext))
1024 return !IsQuitting();
1025 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001026
kthelgasonde6adbe2017-02-22 00:42:11 -08001027 if (cmsLoop != kForever) {
1028 cmsNext = static_cast<int>(TimeUntil(msEnd));
1029 if (cmsNext < 0)
1030 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001031 }
1032 }
1033}
1034
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001035bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1036 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001037 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001038
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001039#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001040 if (need_synchronize_access) {
1041 // We explicitly ask for no rights other than synchronization.
1042 // This gives us the best chance of succeeding.
1043 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1044 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001045 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001046 return false;
1047 }
1048 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001049 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001050#elif defined(WEBRTC_POSIX)
1051 thread_ = pthread_self();
1052#endif
1053 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001054 thread_manager->SetCurrentThread(this);
1055 return true;
1056}
1057
Tommi51492422017-12-04 15:18:23 +01001058bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001059#if defined(WEBRTC_WIN)
1060 return thread_ != nullptr;
1061#elif defined(WEBRTC_POSIX)
1062 return thread_ != 0;
1063#endif
1064}
1065
Steve Antonbcc1a762019-12-11 11:21:53 -08001066// static
1067MessageHandler* Thread::GetPostTaskMessageHandler() {
1068 // Allocate at first call, never deallocate.
1069 static MessageHandler* handler = new MessageHandlerWithTask;
1070 return handler;
1071}
1072
Taylor Brandstetter08672602018-03-02 15:20:33 -08001073AutoThread::AutoThread()
1074 : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001075 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001076 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001077 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1078 // post a message to a queue that no running thread is serving.
1079 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001080 ThreadManager::Instance()->SetCurrentThread(this);
1081 }
1082}
1083
1084AutoThread::~AutoThread() {
1085 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001086 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001087 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001088 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001089 }
1090}
1091
nisse7eaa4ea2017-05-08 05:25:41 -07001092AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001093 : Thread(ss, /*do_init=*/false) {
1094 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001095 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001096 // Temporarily set the current thread to nullptr so that we can keep checks
1097 // around that catch unintentional pointer overwrites.
1098 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001099 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1100 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001101 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001102 }
1103}
1104
1105AutoSocketServerThread::~AutoSocketServerThread() {
1106 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
1107 // Some tests post destroy messages to this thread. To avoid memory
1108 // leaks, we have to process those messages. In particular
1109 // P2PTransportChannelPingTest, relying on the message posted in
1110 // cricket::Connection::Destroy.
1111 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -07001112 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001113 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001114 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1115 // its contents rely on this thread still being set as the current thread.
1116 Stop();
1117 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001118 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001119 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1120 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001121 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001122 }
1123}
1124
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001125} // namespace rtc