blob: 1045398b4c3cde53c7e4b024fc56307b23868868 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013#if defined(WEBRTC_WIN)
14#include <comdef.h>
15#elif defined(WEBRTC_POSIX)
16#include <time.h>
Tommi51492422017-12-04 15:18:23 +010017#else
18#error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#endif
20
Artem Titov80d02ad2018-05-21 12:20:39 +020021#if defined(WEBRTC_WIN)
22// Disable warning that we don't care about:
23// warning C4722: destructor never returns, potential memory leak
24#pragma warning(disable : 4722)
25#endif
26
Yves Gerey988cc082018-10-23 12:03:01 +020027#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020028
Yves Gerey988cc082018-10-23 12:03:01 +020029#include <utility>
Yves Gerey2e00abc2018-10-05 15:39:24 +020030
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010031#include "absl/algorithm/container.h"
32#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020034#include "rtc_base/deprecated/recursive_critical_section.h"
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +020035#include "rtc_base/event.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010036#include "rtc_base/internal/default_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/null_socket_server.h"
Artem Titovdfc5f0d2020-07-03 12:09:26 +020039#include "rtc_base/synchronization/sequence_checker.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010040#include "rtc_base/task_utils/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020044#if defined(WEBRTC_MAC)
45#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020046
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020047/*
48 * These are forward-declarations for methods that are part of the
49 * ObjC runtime. They are declared in the private header objc-internal.h.
50 * These calls are what clang inserts when using @autoreleasepool in ObjC,
51 * but here they are used directly in order to keep this file C++.
52 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
53 */
54extern "C" {
55void* objc_autoreleasePoolPush(void);
56void objc_autoreleasePoolPop(void* pool);
57}
58
59namespace {
60class ScopedAutoReleasePool {
61 public:
62 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
63 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
64
65 private:
66 void* const pool_;
67};
68} // namespace
69#endif
70
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080072namespace {
73
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010074const int kSlowDispatchLoggingThreshold = 50; // 50 ms
75
Steve Antonbcc1a762019-12-11 11:21:53 -080076class MessageHandlerWithTask final : public MessageHandler {
77 public:
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +020078 MessageHandlerWithTask() {}
Steve Antonbcc1a762019-12-11 11:21:53 -080079
80 void OnMessage(Message* msg) override {
81 static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
82 delete msg->pdata;
83 }
84
85 private:
86 ~MessageHandlerWithTask() override {}
87
88 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
89};
90
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010091class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
92 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020093 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
94 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010095 : cs_(cs), processing_(processing) {
96 cs_->Enter();
97 *processing_ += 1;
98 }
99
100 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
101 *processing_ -= 1;
102 cs_->Leave();
103 }
104
105 private:
Markus Handell3cb525b2020-07-16 16:16:09 +0200106 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100107 size_t* processing_;
108
109 RTC_DISALLOW_COPY_AND_ASSIGN(MarkProcessingCritScope);
110};
111
Steve Antonbcc1a762019-12-11 11:21:53 -0800112} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000113
114ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200115 static ThreadManager* const thread_manager = new ThreadManager();
116 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000117}
118
nisse7866cfe2017-04-26 01:45:31 -0700119ThreadManager::~ThreadManager() {
120 // By above RTC_DEFINE_STATIC_LOCAL.
121 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
122}
123
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100125void ThreadManager::Add(Thread* message_queue) {
126 return Instance()->AddInternal(message_queue);
127}
128void ThreadManager::AddInternal(Thread* message_queue) {
129 CritScope cs(&crit_);
130 // Prevent changes while the list of message queues is processed.
131 RTC_DCHECK_EQ(processing_, 0);
132 message_queues_.push_back(message_queue);
133}
134
135// static
136void ThreadManager::Remove(Thread* message_queue) {
137 return Instance()->RemoveInternal(message_queue);
138}
139void ThreadManager::RemoveInternal(Thread* message_queue) {
140 {
141 CritScope cs(&crit_);
142 // Prevent changes while the list of message queues is processed.
143 RTC_DCHECK_EQ(processing_, 0);
144 std::vector<Thread*>::iterator iter;
145 iter = absl::c_find(message_queues_, message_queue);
146 if (iter != message_queues_.end()) {
147 message_queues_.erase(iter);
148 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100149#if RTC_DCHECK_IS_ON
150 RemoveFromSendGraph(message_queue);
151#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100152 }
153}
154
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100155#if RTC_DCHECK_IS_ON
156void ThreadManager::RemoveFromSendGraph(Thread* thread) {
157 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
158 if (it->first == thread) {
159 it = send_graph_.erase(it);
160 } else {
161 it->second.erase(thread);
162 ++it;
163 }
164 }
165}
166
167void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
168 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200169 RTC_DCHECK(source);
170 RTC_DCHECK(target);
171
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100172 CritScope cs(&crit_);
173 std::deque<Thread*> all_targets({target});
174 // We check the pre-existing who-sends-to-who graph for any path from target
175 // to source. This loop is guaranteed to terminate because per the send graph
176 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800177 for (size_t i = 0; i < all_targets.size(); i++) {
178 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100179 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
180 }
181 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
182 << " send loop between " << source->name() << " and " << target->name();
183
184 // We may now insert source -> target without creating a cycle, since there
185 // was no path from target to source per the prior CHECK.
186 send_graph_[source].insert(target);
187}
188#endif
189
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100190// static
191void ThreadManager::Clear(MessageHandler* handler) {
192 return Instance()->ClearInternal(handler);
193}
194void ThreadManager::ClearInternal(MessageHandler* handler) {
195 // Deleted objects may cause re-entrant calls to ClearInternal. This is
196 // allowed as the list of message queues does not change while queues are
197 // cleared.
198 MarkProcessingCritScope cs(&crit_, &processing_);
199 for (Thread* queue : message_queues_) {
200 queue->Clear(handler);
201 }
202}
203
204// static
205void ThreadManager::ProcessAllMessageQueuesForTesting() {
206 return Instance()->ProcessAllMessageQueuesInternal();
207}
208
209void ThreadManager::ProcessAllMessageQueuesInternal() {
210 // This works by posting a delayed message at the current time and waiting
211 // for it to be dispatched on all queues, which will ensure that all messages
212 // that came before it were also dispatched.
213 volatile int queues_not_done = 0;
214
215 // This class is used so that whether the posted message is processed, or the
216 // message queue is simply cleared, queues_not_done gets decremented.
217 class ScopedIncrement : public MessageData {
218 public:
219 ScopedIncrement(volatile int* value) : value_(value) {
220 AtomicOps::Increment(value_);
221 }
222 ~ScopedIncrement() override { AtomicOps::Decrement(value_); }
223
224 private:
225 volatile int* value_;
226 };
227
228 {
229 MarkProcessingCritScope cs(&crit_, &processing_);
230 for (Thread* queue : message_queues_) {
231 if (!queue->IsProcessingMessagesForTesting()) {
232 // If the queue is not processing messages, it can
233 // be ignored. If we tried to post a message to it, it would be dropped
234 // or ignored.
235 continue;
236 }
237 queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
238 new ScopedIncrement(&queues_not_done));
239 }
240 }
241
242 rtc::Thread* current = rtc::Thread::Current();
243 // Note: One of the message queues may have been on this thread, which is
244 // why we can't synchronously wait for queues_not_done to go to 0; we need
245 // to process messages as well.
246 while (AtomicOps::AcquireLoad(&queues_not_done) > 0) {
247 if (current) {
248 current->ProcessMessages(0);
249 }
250 }
251}
252
253// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700255 ThreadManager* manager = ThreadManager::Instance();
256 Thread* thread = manager->CurrentThread();
257
Niels Moller9d1840c2019-05-21 07:26:37 +0000258#ifndef NO_MAIN_THREAD_WRAPPING
259 // Only autowrap the thread which instantiated the ThreadManager.
260 if (!thread && manager->IsMainThread()) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100261 thread = new Thread(CreateDefaultSocketServer());
Niels Moller9d1840c2019-05-21 07:26:37 +0000262 thread->WrapCurrentWithThreadManager(manager, true);
263 }
264#endif
265
nisse7866cfe2017-04-26 01:45:31 -0700266 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267}
268
269#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +0000270ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200271#if defined(WEBRTC_MAC)
272 InitCocoaMultiThreading();
273#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800274 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275}
276
Yves Gerey665174f2018-06-19 15:03:05 +0200277Thread* ThreadManager::CurrentThread() {
278 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000279}
280
Sebastian Jansson178a6852020-01-14 11:12:26 +0100281void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282 pthread_setspecific(key_, thread);
283}
284#endif
285
286#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000287ThreadManager::ThreadManager()
288 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200289
290Thread* ThreadManager::CurrentThread() {
291 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292}
293
Sebastian Jansson178a6852020-01-14 11:12:26 +0100294void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295 TlsSetValue(key_, thread);
296}
297#endif
298
Sebastian Jansson178a6852020-01-14 11:12:26 +0100299void ThreadManager::SetCurrentThread(Thread* thread) {
300#if RTC_DLOG_IS_ON
301 if (CurrentThread() && thread) {
302 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
303 }
304#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200305
306 if (thread) {
307 thread->EnsureIsCurrentTaskQueue();
308 } else {
309 Thread* current = CurrentThread();
310 if (current) {
311 // The current thread is being cleared, e.g. as a result of
312 // UnwrapCurrent() being called or when a thread is being stopped
313 // (see PreRun()). This signals that the Thread instance is being detached
314 // from the thread, which also means that TaskQueue::Current() must not
315 // return a pointer to the Thread instance.
316 current->ClearCurrentTaskQueue();
317 }
318 }
319
Sebastian Jansson178a6852020-01-14 11:12:26 +0100320 SetCurrentThreadInternal(thread);
321}
322
323void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
324 SetCurrentThreadInternal(thread);
325}
326
Yves Gerey665174f2018-06-19 15:03:05 +0200327Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000328 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800329 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100330 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000331 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000332 }
333 return result;
334}
335
336void ThreadManager::UnwrapCurrentThread() {
337 Thread* t = CurrentThread();
338 if (t && !(t->IsOwned())) {
339 t->UnwrapCurrent();
340 delete t;
341 }
342}
343
Niels Moller9d1840c2019-05-21 07:26:37 +0000344bool ThreadManager::IsMainThread() {
345 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
346}
347
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000348Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200349 : thread_(Thread::Current()),
350 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000351
352Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800353 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000354 thread_->SetAllowBlockingCalls(previous_state_);
355}
356
Taylor Brandstetter08672602018-03-02 15:20:33 -0800357Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700358
359Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800360 : Thread(std::move(ss), /*do_init=*/true) {}
361
362Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100363 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100364 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100365 fInitialized_(false),
366 fDestroyed_(false),
367 stop_(0),
368 ss_(ss) {
369 RTC_DCHECK(ss);
370 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800371 SetName("Thread", this); // default name
372 if (do_init) {
373 DoInit();
374 }
375}
376
377Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100378 : Thread(ss.get(), do_init) {
379 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000380}
381
382Thread::~Thread() {
383 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800384 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000385}
386
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100387void Thread::DoInit() {
388 if (fInitialized_) {
389 return;
390 }
391
392 fInitialized_ = true;
393 ThreadManager::Add(this);
394}
395
396void Thread::DoDestroy() {
397 if (fDestroyed_) {
398 return;
399 }
400
401 fDestroyed_ = true;
402 // The signal is done from here to ensure
403 // that it always gets called when the queue
404 // is going away.
405 SignalQueueDestroyed();
406 ThreadManager::Remove(this);
407 ClearInternal(nullptr, MQID_ANY, nullptr);
408
409 if (ss_) {
410 ss_->SetMessageQueue(nullptr);
411 }
412}
413
414SocketServer* Thread::socketserver() {
415 return ss_;
416}
417
418void Thread::WakeUpSocketServer() {
419 ss_->WakeUp();
420}
421
422void Thread::Quit() {
423 AtomicOps::ReleaseStore(&stop_, 1);
424 WakeUpSocketServer();
425}
426
427bool Thread::IsQuitting() {
428 return AtomicOps::AcquireLoad(&stop_) != 0;
429}
430
431void Thread::Restart() {
432 AtomicOps::ReleaseStore(&stop_, 0);
433}
434
435bool Thread::Peek(Message* pmsg, int cmsWait) {
436 if (fPeekKeep_) {
437 *pmsg = msgPeek_;
438 return true;
439 }
440 if (!Get(pmsg, cmsWait))
441 return false;
442 msgPeek_ = *pmsg;
443 fPeekKeep_ = true;
444 return true;
445}
446
447bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
448 // Return and clear peek if present
449 // Always return the peek if it exists so there is Peek/Get symmetry
450
451 if (fPeekKeep_) {
452 *pmsg = msgPeek_;
453 fPeekKeep_ = false;
454 return true;
455 }
456
457 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
458
459 int64_t cmsTotal = cmsWait;
460 int64_t cmsElapsed = 0;
461 int64_t msStart = TimeMillis();
462 int64_t msCurrent = msStart;
463 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100464 // Check for posted events
465 int64_t cmsDelayNext = kForever;
466 bool first_pass = true;
467 while (true) {
468 // All queue operations need to be locked, but nothing else in this loop
469 // (specifically handling disposed message) can happen inside the crit.
470 // Otherwise, disposed MessageHandlers will cause deadlocks.
471 {
472 CritScope cs(&crit_);
473 // On the first pass, check for delayed messages that have been
474 // triggered and calculate the next trigger time.
475 if (first_pass) {
476 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100477 while (!delayed_messages_.empty()) {
478 if (msCurrent < delayed_messages_.top().run_time_ms_) {
479 cmsDelayNext =
480 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100481 break;
482 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100483 messages_.push_back(delayed_messages_.top().msg_);
484 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100485 }
486 }
487 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100488 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100489 break;
490 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100491 *pmsg = messages_.front();
492 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100493 }
494 } // crit_ is released here.
495
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100496 // If this was a dispose message, delete it and skip it.
497 if (MQID_DISPOSE == pmsg->message_id) {
498 RTC_DCHECK(nullptr == pmsg->phandler);
499 delete pmsg->pdata;
500 *pmsg = Message();
501 continue;
502 }
503 return true;
504 }
505
506 if (IsQuitting())
507 break;
508
509 // Which is shorter, the delay wait or the asked wait?
510
511 int64_t cmsNext;
512 if (cmsWait == kForever) {
513 cmsNext = cmsDelayNext;
514 } else {
515 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
516 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
517 cmsNext = cmsDelayNext;
518 }
519
520 {
521 // Wait and multiplex in the meantime
522 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
523 return false;
524 }
525
526 // If the specified timeout expired, return
527
528 msCurrent = TimeMillis();
529 cmsElapsed = TimeDiff(msCurrent, msStart);
530 if (cmsWait != kForever) {
531 if (cmsElapsed >= cmsWait)
532 return false;
533 }
534 }
535 return false;
536}
537
538void Thread::Post(const Location& posted_from,
539 MessageHandler* phandler,
540 uint32_t id,
541 MessageData* pdata,
542 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100543 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100544 if (IsQuitting()) {
545 delete pdata;
546 return;
547 }
548
549 // Keep thread safe
550 // Add the message to the end of the queue
551 // Signal for the multiplexer to return
552
553 {
554 CritScope cs(&crit_);
555 Message msg;
556 msg.posted_from = posted_from;
557 msg.phandler = phandler;
558 msg.message_id = id;
559 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100560 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100561 }
562 WakeUpSocketServer();
563}
564
565void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100566 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100567 MessageHandler* phandler,
568 uint32_t id,
569 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100570 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100571 pdata);
572}
573
574void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100575 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100576 MessageHandler* phandler,
577 uint32_t id,
578 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100579 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100580 pdata);
581}
582
583void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100584 int64_t delay_ms,
585 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100586 MessageHandler* phandler,
587 uint32_t id,
588 MessageData* pdata) {
589 if (IsQuitting()) {
590 delete pdata;
591 return;
592 }
593
594 // Keep thread safe
595 // Add to the priority queue. Gets sorted soonest first.
596 // Signal for the multiplexer to return.
597
598 {
599 CritScope cs(&crit_);
600 Message msg;
601 msg.posted_from = posted_from;
602 msg.phandler = phandler;
603 msg.message_id = id;
604 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100605 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
606 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100607 // If this message queue processes 1 message every millisecond for 50 days,
608 // we will wrap this number. Even then, only messages with identical times
609 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100610 ++delayed_next_num_;
611 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100612 }
613 WakeUpSocketServer();
614}
615
616int Thread::GetDelay() {
617 CritScope cs(&crit_);
618
Sebastian Jansson61380c02020-01-17 14:46:08 +0100619 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100620 return 0;
621
Sebastian Jansson61380c02020-01-17 14:46:08 +0100622 if (!delayed_messages_.empty()) {
623 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100624 if (delay < 0)
625 delay = 0;
626 return delay;
627 }
628
629 return kForever;
630}
631
632void Thread::ClearInternal(MessageHandler* phandler,
633 uint32_t id,
634 MessageList* removed) {
635 // Remove messages with phandler
636
637 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
638 if (removed) {
639 removed->push_back(msgPeek_);
640 } else {
641 delete msgPeek_.pdata;
642 }
643 fPeekKeep_ = false;
644 }
645
646 // Remove from ordered message queue
647
Sebastian Jansson61380c02020-01-17 14:46:08 +0100648 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100649 if (it->Match(phandler, id)) {
650 if (removed) {
651 removed->push_back(*it);
652 } else {
653 delete it->pdata;
654 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100655 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100656 } else {
657 ++it;
658 }
659 }
660
661 // Remove from priority queue. Not directly iterable, so use this approach
662
Sebastian Jansson61380c02020-01-17 14:46:08 +0100663 auto new_end = delayed_messages_.container().begin();
664 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100665 if (it->msg_.Match(phandler, id)) {
666 if (removed) {
667 removed->push_back(it->msg_);
668 } else {
669 delete it->msg_.pdata;
670 }
671 } else {
672 *new_end++ = *it;
673 }
674 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100675 delayed_messages_.container().erase(new_end,
676 delayed_messages_.container().end());
677 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100678}
679
680void Thread::Dispatch(Message* pmsg) {
681 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
682 pmsg->posted_from.file_name(), "src_func",
683 pmsg->posted_from.function_name());
684 int64_t start_time = TimeMillis();
685 pmsg->phandler->OnMessage(pmsg);
686 int64_t end_time = TimeMillis();
687 int64_t diff = TimeDiff(end_time, start_time);
688 if (diff >= kSlowDispatchLoggingThreshold) {
689 RTC_LOG(LS_INFO) << "Message took " << diff
690 << "ms to dispatch. Posted from: "
691 << pmsg->posted_from.ToString();
692 }
693}
694
nisse7866cfe2017-04-26 01:45:31 -0700695bool Thread::IsCurrent() const {
696 return ThreadManager::Instance()->CurrentThread() == this;
697}
698
danilchapbebf54c2016-04-28 01:32:48 -0700699std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100700 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700701}
702
703std::unique_ptr<Thread> Thread::Create() {
704 return std::unique_ptr<Thread>(
705 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
706}
707
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000708bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000709 AssertBlockingIsAllowedOnCurrentThread();
710
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000711#if defined(WEBRTC_WIN)
712 ::Sleep(milliseconds);
713 return true;
714#else
715 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
716 // so we use nanosleep() even though it has greater precision than necessary.
717 struct timespec ts;
718 ts.tv_sec = milliseconds / 1000;
719 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800720 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000721 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100722 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000723 return false;
724 }
725 return true;
726#endif
727}
728
729bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100730 RTC_DCHECK(!IsRunning());
731
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000732 name_ = name;
733 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200734 // The %p specifier typically produce at most 16 hex digits, possibly with a
735 // 0x prefix. But format is implementation defined, so add some margin.
736 char buf[30];
737 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000738 name_ += buf;
739 }
740 return true;
741}
742
Niels Möllerd2e50132019-06-11 09:24:14 +0200743bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100744 RTC_DCHECK(!IsRunning());
745
746 if (IsRunning())
747 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000748
André Susano Pinto02a57972016-07-22 13:30:05 +0200749 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000750
751 // Make sure that ThreadManager is created on the main thread before
752 // we start a new thread.
753 ThreadManager::Instance();
754
Tommi51492422017-12-04 15:18:23 +0100755 owned_ = true;
756
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000757#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200758 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100759 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000760 return false;
761 }
762#elif defined(WEBRTC_POSIX)
763 pthread_attr_t attr;
764 pthread_attr_init(&attr);
765
Niels Möllerd2e50132019-06-11 09:24:14 +0200766 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000767 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100768 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100769 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000770 return false;
771 }
Tommi51492422017-12-04 15:18:23 +0100772 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000773#endif
774 return true;
775}
776
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000777bool Thread::WrapCurrent() {
778 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
779}
780
781void Thread::UnwrapCurrent() {
782 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800783 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000784#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800785 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000786 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100787 RTC_LOG_GLE(LS_ERROR)
788 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000789 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800790 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100791 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000792 }
Tommi51492422017-12-04 15:18:23 +0100793#elif defined(WEBRTC_POSIX)
794 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000795#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000796}
797
798void Thread::SafeWrapCurrent() {
799 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
800}
801
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000802void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100803 if (!IsRunning())
804 return;
805
806 RTC_DCHECK(!IsCurrent());
807 if (Current() && !Current()->blocking_calls_allowed_) {
808 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100809 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100810 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000811
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000812#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100813 RTC_DCHECK(thread_ != nullptr);
814 WaitForSingleObject(thread_, INFINITE);
815 CloseHandle(thread_);
816 thread_ = nullptr;
817 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000818#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100819 pthread_join(thread_, nullptr);
820 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000821#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000822}
823
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000824bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800825 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000826 bool previous = blocking_calls_allowed_;
827 blocking_calls_allowed_ = allow;
828 return previous;
829}
830
831// static
832void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700833#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000834 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800835 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000836#endif
837}
838
deadbeefdc20e262017-01-31 15:10:44 -0800839// static
840#if defined(WEBRTC_WIN)
841DWORD WINAPI Thread::PreRun(LPVOID pv) {
842#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000843void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800844#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200845 Thread* thread = static_cast<Thread*>(pv);
846 ThreadManager::Instance()->SetCurrentThread(thread);
847 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200848#if defined(WEBRTC_MAC)
849 ScopedAutoReleasePool pool;
850#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200851 thread->Run();
852
Tommi51492422017-12-04 15:18:23 +0100853 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800854#ifdef WEBRTC_WIN
855 return 0;
856#else
857 return nullptr;
858#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200859} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000860
861void Thread::Run() {
862 ProcessMessages(kForever);
863}
864
865bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100866 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000867 return owned_;
868}
869
870void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100871 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000872 Join();
873}
874
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700875void Thread::Send(const Location& posted_from,
876 MessageHandler* phandler,
877 uint32_t id,
878 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100879 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200880 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000881 return;
882
883 // Sent messages are sent to the MessageHandler directly, in the context
884 // of "thread", like Win32 SendMessage. If in the right context,
885 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000886 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700887 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000888 msg.phandler = phandler;
889 msg.message_id = id;
890 msg.pdata = pdata;
891 if (IsCurrent()) {
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100892 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000893 return;
894 }
895
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000896 AssertBlockingIsAllowedOnCurrentThread();
897
Yves Gerey665174f2018-06-19 15:03:05 +0200898 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200899
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100900#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200901 if (current_thread) {
902 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
903 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
904 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000905 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200906#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000907
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200908 // Perhaps down the line we can get rid of this workaround and always require
909 // current_thread to be valid when Send() is called.
910 std::unique_ptr<rtc::Event> done_event;
911 if (!current_thread)
912 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000913
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200914 bool ready = false;
915 PostTask(webrtc::ToQueuedTask(
916 [&msg]() mutable { msg.phandler->OnMessage(&msg); },
917 [this, &ready, current_thread, done = done_event.get()] {
918 if (current_thread) {
919 CritScope cs(&crit_);
920 ready = true;
921 current_thread->socketserver()->WakeUp();
922 } else {
923 done->Set();
924 }
925 }));
926
927 if (current_thread) {
928 bool waited = false;
929 crit_.Enter();
930 while (!ready) {
931 crit_.Leave();
932 current_thread->socketserver()->Wait(kForever, false);
933 waited = true;
934 crit_.Enter();
935 }
936 crit_.Leave();
937
938 // Our Wait loop above may have consumed some WakeUp events for this
939 // Thread, that weren't relevant to this Send. Losing these WakeUps can
940 // cause problems for some SocketServers.
941 //
942 // Concrete example:
943 // Win32SocketServer on thread A calls Send on thread B. While processing
944 // the message, thread B Posts a message to A. We consume the wakeup for
945 // that Post while waiting for the Send to complete, which means that when
946 // we exit this loop, we need to issue another WakeUp, or else the Posted
947 // message won't be processed in a timely manner.
948
949 if (waited) {
950 current_thread->socketserver()->WakeUp();
951 }
952 } else {
953 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000954 }
955}
956
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700957void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100958 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800959 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
960 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100961
962 class FunctorMessageHandler : public MessageHandler {
963 public:
964 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +0200965 : functor_(functor) {}
Danil Chapovalov89313452019-11-29 12:56:43 +0100966 void OnMessage(Message* msg) override { functor_(); }
967
968 private:
969 rtc::FunctionView<void()> functor_;
970 } handler(functor);
971
972 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000973}
974
Tommi6866dc72020-05-15 10:11:56 +0200975// Called by the ThreadManager when being set as the current thread.
976void Thread::EnsureIsCurrentTaskQueue() {
977 task_queue_registration_ =
978 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
979}
980
981// Called by the ThreadManager when being set as the current thread.
982void Thread::ClearCurrentTaskQueue() {
983 task_queue_registration_.reset();
984}
985
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100986void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
987 RTC_DCHECK(msg);
988 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
989 std::unique_ptr<webrtc::QueuedTask> task = std::move(data->data());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100990 // Thread expects handler to own Message::pdata when OnMessage is called
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100991 // Since MessageData is no longer needed, delete it.
992 delete data;
993
994 // QueuedTask interface uses Run return value to communicate who owns the
995 // task. false means QueuedTask took the ownership.
996 if (!task->Run())
997 task.release();
998}
999
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001000void Thread::AllowInvokesToThread(Thread* thread) {
1001#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1002 if (!IsCurrent()) {
1003 PostTask(webrtc::ToQueuedTask(
1004 [thread, this]() { AllowInvokesToThread(thread); }));
1005 return;
1006 }
1007 RTC_DCHECK_RUN_ON(this);
1008 allowed_threads_.push_back(thread);
1009 invoke_policy_enabled_ = true;
1010#endif
1011}
1012
1013void Thread::DisallowAllInvokes() {
1014#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1015 if (!IsCurrent()) {
1016 PostTask(webrtc::ToQueuedTask([this]() { DisallowAllInvokes(); }));
1017 return;
1018 }
1019 RTC_DCHECK_RUN_ON(this);
1020 allowed_threads_.clear();
1021 invoke_policy_enabled_ = true;
1022#endif
1023}
1024
1025// Returns true if no policies added or if there is at least one policy
1026// that permits invocation to |target| thread.
1027bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
1028#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1029 RTC_DCHECK_RUN_ON(this);
1030 if (!invoke_policy_enabled_) {
1031 return true;
1032 }
1033 for (const auto* thread : allowed_threads_) {
1034 if (thread == target) {
1035 return true;
1036 }
1037 }
1038 return false;
1039#else
1040 return true;
1041#endif
1042}
1043
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001044void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
1045 // Though Post takes MessageData by raw pointer (last parameter), it still
1046 // takes it with ownership.
1047 Post(RTC_FROM_HERE, &queued_task_handler_,
1048 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1049}
1050
1051void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
1052 uint32_t milliseconds) {
1053 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1054 // it still takes it with ownership.
1055 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
1056 /*id=*/0,
1057 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1058}
1059
1060void Thread::Delete() {
1061 Stop();
1062 delete this;
1063}
1064
Niels Möller8909a632018-09-06 08:42:44 +02001065bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001066 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001067}
1068
Peter Boström0c4e06b2015-10-07 12:23:21 +02001069void Thread::Clear(MessageHandler* phandler,
1070 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001071 MessageList* removed) {
1072 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001073 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001074}
1075
1076bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001077 // Using ProcessMessages with a custom clock for testing and a time greater
1078 // than 0 doesn't work, since it's not guaranteed to advance the custom
1079 // clock's time, and may get stuck in an infinite loop.
1080 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1081 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001082 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001083 int cmsNext = cmsLoop;
1084
1085 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001086#if defined(WEBRTC_MAC)
1087 ScopedAutoReleasePool pool;
1088#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001089 Message msg;
1090 if (!Get(&msg, cmsNext))
1091 return !IsQuitting();
1092 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001093
kthelgasonde6adbe2017-02-22 00:42:11 -08001094 if (cmsLoop != kForever) {
1095 cmsNext = static_cast<int>(TimeUntil(msEnd));
1096 if (cmsNext < 0)
1097 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001098 }
1099 }
1100}
1101
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001102bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1103 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001104 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001105
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001106#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001107 if (need_synchronize_access) {
1108 // We explicitly ask for no rights other than synchronization.
1109 // This gives us the best chance of succeeding.
1110 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1111 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001112 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001113 return false;
1114 }
1115 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001116 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001117#elif defined(WEBRTC_POSIX)
1118 thread_ = pthread_self();
1119#endif
1120 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001121 thread_manager->SetCurrentThread(this);
1122 return true;
1123}
1124
Tommi51492422017-12-04 15:18:23 +01001125bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001126#if defined(WEBRTC_WIN)
1127 return thread_ != nullptr;
1128#elif defined(WEBRTC_POSIX)
1129 return thread_ != 0;
1130#endif
1131}
1132
Steve Antonbcc1a762019-12-11 11:21:53 -08001133// static
1134MessageHandler* Thread::GetPostTaskMessageHandler() {
1135 // Allocate at first call, never deallocate.
1136 static MessageHandler* handler = new MessageHandlerWithTask;
1137 return handler;
1138}
1139
Taylor Brandstetter08672602018-03-02 15:20:33 -08001140AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +01001141 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001142 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001143 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001144 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1145 // post a message to a queue that no running thread is serving.
1146 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001147 ThreadManager::Instance()->SetCurrentThread(this);
1148 }
1149}
1150
1151AutoThread::~AutoThread() {
1152 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001153 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001154 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001155 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001156 }
1157}
1158
nisse7eaa4ea2017-05-08 05:25:41 -07001159AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001160 : Thread(ss, /*do_init=*/false) {
1161 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001162 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001163 // Temporarily set the current thread to nullptr so that we can keep checks
1164 // around that catch unintentional pointer overwrites.
1165 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001166 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1167 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001168 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001169 }
1170}
1171
1172AutoSocketServerThread::~AutoSocketServerThread() {
1173 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
1174 // Some tests post destroy messages to this thread. To avoid memory
1175 // leaks, we have to process those messages. In particular
1176 // P2PTransportChannelPingTest, relying on the message posted in
1177 // cricket::Connection::Destroy.
1178 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -07001179 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001180 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001181 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1182 // its contents rely on this thread still being set as the current thread.
1183 Stop();
1184 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001185 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001186 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1187 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001188 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001189 }
1190}
1191
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001192} // namespace rtc