blob: b0b0e52a070d1e3a3a3e6528599e316b7e3a963a [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"
Artem Titovd15a5752021-02-10 14:31:24 +010032#include "api/sequence_checker.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010033#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020035#include "rtc_base/deprecated/recursive_critical_section.h"
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +020036#include "rtc_base/event.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010037#include "rtc_base/internal/default_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "rtc_base/null_socket_server.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010040#include "rtc_base/task_utils/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020044#if defined(WEBRTC_MAC)
45#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020046
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020047/*
48 * These are forward-declarations for methods that are part of the
49 * ObjC runtime. They are declared in the private header objc-internal.h.
50 * These calls are what clang inserts when using @autoreleasepool in ObjC,
51 * but here they are used directly in order to keep this file C++.
52 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
53 */
54extern "C" {
55void* objc_autoreleasePoolPush(void);
56void objc_autoreleasePoolPop(void* pool);
57}
58
59namespace {
60class ScopedAutoReleasePool {
61 public:
62 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
63 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
64
65 private:
66 void* const pool_;
67};
68} // namespace
69#endif
70
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080072namespace {
73
74class MessageHandlerWithTask final : public MessageHandler {
75 public:
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +020076 MessageHandlerWithTask() {}
Steve Antonbcc1a762019-12-11 11:21:53 -080077
78 void OnMessage(Message* msg) override {
79 static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
80 delete msg->pdata;
81 }
82
83 private:
84 ~MessageHandlerWithTask() override {}
85
86 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
87};
88
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010089class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
90 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020091 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
92 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010093 : cs_(cs), processing_(processing) {
94 cs_->Enter();
95 *processing_ += 1;
96 }
97
98 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
99 *processing_ -= 1;
100 cs_->Leave();
101 }
102
103 private:
Markus Handell3cb525b2020-07-16 16:16:09 +0200104 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100105 size_t* processing_;
106
107 RTC_DISALLOW_COPY_AND_ASSIGN(MarkProcessingCritScope);
108};
109
Steve Antonbcc1a762019-12-11 11:21:53 -0800110} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111
112ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200113 static ThreadManager* const thread_manager = new ThreadManager();
114 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115}
116
nisse7866cfe2017-04-26 01:45:31 -0700117ThreadManager::~ThreadManager() {
118 // By above RTC_DEFINE_STATIC_LOCAL.
119 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
120}
121
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000122// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100123void ThreadManager::Add(Thread* message_queue) {
124 return Instance()->AddInternal(message_queue);
125}
126void ThreadManager::AddInternal(Thread* message_queue) {
127 CritScope cs(&crit_);
128 // Prevent changes while the list of message queues is processed.
129 RTC_DCHECK_EQ(processing_, 0);
130 message_queues_.push_back(message_queue);
131}
132
133// static
134void ThreadManager::Remove(Thread* message_queue) {
135 return Instance()->RemoveInternal(message_queue);
136}
137void ThreadManager::RemoveInternal(Thread* message_queue) {
138 {
139 CritScope cs(&crit_);
140 // Prevent changes while the list of message queues is processed.
141 RTC_DCHECK_EQ(processing_, 0);
142 std::vector<Thread*>::iterator iter;
143 iter = absl::c_find(message_queues_, message_queue);
144 if (iter != message_queues_.end()) {
145 message_queues_.erase(iter);
146 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100147#if RTC_DCHECK_IS_ON
148 RemoveFromSendGraph(message_queue);
149#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100150 }
151}
152
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100153#if RTC_DCHECK_IS_ON
154void ThreadManager::RemoveFromSendGraph(Thread* thread) {
155 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
156 if (it->first == thread) {
157 it = send_graph_.erase(it);
158 } else {
159 it->second.erase(thread);
160 ++it;
161 }
162 }
163}
164
165void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
166 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200167 RTC_DCHECK(source);
168 RTC_DCHECK(target);
169
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100170 CritScope cs(&crit_);
171 std::deque<Thread*> all_targets({target});
172 // We check the pre-existing who-sends-to-who graph for any path from target
173 // to source. This loop is guaranteed to terminate because per the send graph
174 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800175 for (size_t i = 0; i < all_targets.size(); i++) {
176 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100177 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
178 }
179 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
180 << " send loop between " << source->name() << " and " << target->name();
181
182 // We may now insert source -> target without creating a cycle, since there
183 // was no path from target to source per the prior CHECK.
184 send_graph_[source].insert(target);
185}
186#endif
187
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100188// static
189void ThreadManager::Clear(MessageHandler* handler) {
190 return Instance()->ClearInternal(handler);
191}
192void ThreadManager::ClearInternal(MessageHandler* handler) {
193 // Deleted objects may cause re-entrant calls to ClearInternal. This is
194 // allowed as the list of message queues does not change while queues are
195 // cleared.
196 MarkProcessingCritScope cs(&crit_, &processing_);
197 for (Thread* queue : message_queues_) {
198 queue->Clear(handler);
199 }
200}
201
202// static
203void ThreadManager::ProcessAllMessageQueuesForTesting() {
204 return Instance()->ProcessAllMessageQueuesInternal();
205}
206
207void ThreadManager::ProcessAllMessageQueuesInternal() {
208 // This works by posting a delayed message at the current time and waiting
209 // for it to be dispatched on all queues, which will ensure that all messages
210 // that came before it were also dispatched.
211 volatile int queues_not_done = 0;
212
213 // This class is used so that whether the posted message is processed, or the
214 // message queue is simply cleared, queues_not_done gets decremented.
215 class ScopedIncrement : public MessageData {
216 public:
217 ScopedIncrement(volatile int* value) : value_(value) {
218 AtomicOps::Increment(value_);
219 }
220 ~ScopedIncrement() override { AtomicOps::Decrement(value_); }
221
222 private:
223 volatile int* value_;
224 };
225
226 {
227 MarkProcessingCritScope cs(&crit_, &processing_);
228 for (Thread* queue : message_queues_) {
229 if (!queue->IsProcessingMessagesForTesting()) {
230 // If the queue is not processing messages, it can
231 // be ignored. If we tried to post a message to it, it would be dropped
232 // or ignored.
233 continue;
234 }
235 queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
236 new ScopedIncrement(&queues_not_done));
237 }
238 }
239
240 rtc::Thread* current = rtc::Thread::Current();
241 // Note: One of the message queues may have been on this thread, which is
242 // why we can't synchronously wait for queues_not_done to go to 0; we need
243 // to process messages as well.
244 while (AtomicOps::AcquireLoad(&queues_not_done) > 0) {
245 if (current) {
246 current->ProcessMessages(0);
247 }
248 }
249}
250
251// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700253 ThreadManager* manager = ThreadManager::Instance();
254 Thread* thread = manager->CurrentThread();
255
Niels Moller9d1840c2019-05-21 07:26:37 +0000256#ifndef NO_MAIN_THREAD_WRAPPING
257 // Only autowrap the thread which instantiated the ThreadManager.
258 if (!thread && manager->IsMainThread()) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100259 thread = new Thread(CreateDefaultSocketServer());
Niels Moller9d1840c2019-05-21 07:26:37 +0000260 thread->WrapCurrentWithThreadManager(manager, true);
261 }
262#endif
263
nisse7866cfe2017-04-26 01:45:31 -0700264 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265}
266
267#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +0000268ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200269#if defined(WEBRTC_MAC)
270 InitCocoaMultiThreading();
271#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800272 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273}
274
Yves Gerey665174f2018-06-19 15:03:05 +0200275Thread* ThreadManager::CurrentThread() {
276 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277}
278
Sebastian Jansson178a6852020-01-14 11:12:26 +0100279void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000280 pthread_setspecific(key_, thread);
281}
282#endif
283
284#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000285ThreadManager::ThreadManager()
286 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200287
288Thread* ThreadManager::CurrentThread() {
289 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290}
291
Sebastian Jansson178a6852020-01-14 11:12:26 +0100292void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293 TlsSetValue(key_, thread);
294}
295#endif
296
Sebastian Jansson178a6852020-01-14 11:12:26 +0100297void ThreadManager::SetCurrentThread(Thread* thread) {
298#if RTC_DLOG_IS_ON
299 if (CurrentThread() && thread) {
300 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
301 }
302#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200303
304 if (thread) {
305 thread->EnsureIsCurrentTaskQueue();
306 } else {
307 Thread* current = CurrentThread();
308 if (current) {
309 // The current thread is being cleared, e.g. as a result of
310 // UnwrapCurrent() being called or when a thread is being stopped
311 // (see PreRun()). This signals that the Thread instance is being detached
312 // from the thread, which also means that TaskQueue::Current() must not
313 // return a pointer to the Thread instance.
314 current->ClearCurrentTaskQueue();
315 }
316 }
317
Sebastian Jansson178a6852020-01-14 11:12:26 +0100318 SetCurrentThreadInternal(thread);
319}
320
321void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
322 SetCurrentThreadInternal(thread);
323}
324
Yves Gerey665174f2018-06-19 15:03:05 +0200325Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800327 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100328 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000329 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330 }
331 return result;
332}
333
334void ThreadManager::UnwrapCurrentThread() {
335 Thread* t = CurrentThread();
336 if (t && !(t->IsOwned())) {
337 t->UnwrapCurrent();
338 delete t;
339 }
340}
341
Niels Moller9d1840c2019-05-21 07:26:37 +0000342bool ThreadManager::IsMainThread() {
343 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
344}
345
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000346Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200347 : thread_(Thread::Current()),
348 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000349
350Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800351 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000352 thread_->SetAllowBlockingCalls(previous_state_);
353}
354
Tommife041642021-04-07 10:08:28 +0200355#if RTC_DCHECK_IS_ON
356Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls(
357 std::function<void(uint32_t, uint32_t)> callback)
358 : thread_(Thread::Current()),
359 base_blocking_call_count_(thread_->GetBlockingCallCount()),
360 base_could_be_blocking_call_count_(
361 thread_->GetCouldBeBlockingCallCount()),
362 result_callback_(std::move(callback)) {}
363
364Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() {
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200365 if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) {
366 result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount());
367 }
Tommife041642021-04-07 10:08:28 +0200368}
369
370uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const {
371 return thread_->GetBlockingCallCount() - base_blocking_call_count_;
372}
373
374uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const {
375 return thread_->GetCouldBeBlockingCallCount() -
376 base_could_be_blocking_call_count_;
377}
378
379uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const {
380 return GetBlockingCallCount() + GetCouldBeBlockingCallCount();
381}
382#endif
383
Taylor Brandstetter08672602018-03-02 15:20:33 -0800384Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700385
386Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800387 : Thread(std::move(ss), /*do_init=*/true) {}
388
389Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100390 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100391 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100392 fInitialized_(false),
393 fDestroyed_(false),
394 stop_(0),
395 ss_(ss) {
396 RTC_DCHECK(ss);
397 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800398 SetName("Thread", this); // default name
399 if (do_init) {
400 DoInit();
401 }
402}
403
404Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100405 : Thread(ss.get(), do_init) {
406 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000407}
408
409Thread::~Thread() {
410 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800411 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412}
413
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100414void Thread::DoInit() {
415 if (fInitialized_) {
416 return;
417 }
418
419 fInitialized_ = true;
420 ThreadManager::Add(this);
421}
422
423void Thread::DoDestroy() {
424 if (fDestroyed_) {
425 return;
426 }
427
428 fDestroyed_ = true;
429 // The signal is done from here to ensure
430 // that it always gets called when the queue
431 // is going away.
432 SignalQueueDestroyed();
433 ThreadManager::Remove(this);
434 ClearInternal(nullptr, MQID_ANY, nullptr);
435
436 if (ss_) {
437 ss_->SetMessageQueue(nullptr);
438 }
439}
440
441SocketServer* Thread::socketserver() {
442 return ss_;
443}
444
445void Thread::WakeUpSocketServer() {
446 ss_->WakeUp();
447}
448
449void Thread::Quit() {
450 AtomicOps::ReleaseStore(&stop_, 1);
451 WakeUpSocketServer();
452}
453
454bool Thread::IsQuitting() {
455 return AtomicOps::AcquireLoad(&stop_) != 0;
456}
457
458void Thread::Restart() {
459 AtomicOps::ReleaseStore(&stop_, 0);
460}
461
462bool Thread::Peek(Message* pmsg, int cmsWait) {
463 if (fPeekKeep_) {
464 *pmsg = msgPeek_;
465 return true;
466 }
467 if (!Get(pmsg, cmsWait))
468 return false;
469 msgPeek_ = *pmsg;
470 fPeekKeep_ = true;
471 return true;
472}
473
474bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
475 // Return and clear peek if present
476 // Always return the peek if it exists so there is Peek/Get symmetry
477
478 if (fPeekKeep_) {
479 *pmsg = msgPeek_;
480 fPeekKeep_ = false;
481 return true;
482 }
483
484 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
485
486 int64_t cmsTotal = cmsWait;
487 int64_t cmsElapsed = 0;
488 int64_t msStart = TimeMillis();
489 int64_t msCurrent = msStart;
490 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100491 // Check for posted events
492 int64_t cmsDelayNext = kForever;
493 bool first_pass = true;
494 while (true) {
495 // All queue operations need to be locked, but nothing else in this loop
496 // (specifically handling disposed message) can happen inside the crit.
497 // Otherwise, disposed MessageHandlers will cause deadlocks.
498 {
499 CritScope cs(&crit_);
500 // On the first pass, check for delayed messages that have been
501 // triggered and calculate the next trigger time.
502 if (first_pass) {
503 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100504 while (!delayed_messages_.empty()) {
505 if (msCurrent < delayed_messages_.top().run_time_ms_) {
506 cmsDelayNext =
507 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100508 break;
509 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100510 messages_.push_back(delayed_messages_.top().msg_);
511 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100512 }
513 }
514 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100515 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100516 break;
517 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100518 *pmsg = messages_.front();
519 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100520 }
521 } // crit_ is released here.
522
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100523 // If this was a dispose message, delete it and skip it.
524 if (MQID_DISPOSE == pmsg->message_id) {
525 RTC_DCHECK(nullptr == pmsg->phandler);
526 delete pmsg->pdata;
527 *pmsg = Message();
528 continue;
529 }
530 return true;
531 }
532
533 if (IsQuitting())
534 break;
535
536 // Which is shorter, the delay wait or the asked wait?
537
538 int64_t cmsNext;
539 if (cmsWait == kForever) {
540 cmsNext = cmsDelayNext;
541 } else {
542 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
543 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
544 cmsNext = cmsDelayNext;
545 }
546
547 {
548 // Wait and multiplex in the meantime
549 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
550 return false;
551 }
552
553 // If the specified timeout expired, return
554
555 msCurrent = TimeMillis();
556 cmsElapsed = TimeDiff(msCurrent, msStart);
557 if (cmsWait != kForever) {
558 if (cmsElapsed >= cmsWait)
559 return false;
560 }
561 }
562 return false;
563}
564
565void Thread::Post(const Location& posted_from,
566 MessageHandler* phandler,
567 uint32_t id,
568 MessageData* pdata,
569 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100570 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100571 if (IsQuitting()) {
572 delete pdata;
573 return;
574 }
575
576 // Keep thread safe
577 // Add the message to the end of the queue
578 // Signal for the multiplexer to return
579
580 {
581 CritScope cs(&crit_);
582 Message msg;
583 msg.posted_from = posted_from;
584 msg.phandler = phandler;
585 msg.message_id = id;
586 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100587 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100588 }
589 WakeUpSocketServer();
590}
591
592void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100593 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100594 MessageHandler* phandler,
595 uint32_t id,
596 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100597 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100598 pdata);
599}
600
601void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100602 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100603 MessageHandler* phandler,
604 uint32_t id,
605 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100606 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100607 pdata);
608}
609
610void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100611 int64_t delay_ms,
612 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100613 MessageHandler* phandler,
614 uint32_t id,
615 MessageData* pdata) {
616 if (IsQuitting()) {
617 delete pdata;
618 return;
619 }
620
621 // Keep thread safe
622 // Add to the priority queue. Gets sorted soonest first.
623 // Signal for the multiplexer to return.
624
625 {
626 CritScope cs(&crit_);
627 Message msg;
628 msg.posted_from = posted_from;
629 msg.phandler = phandler;
630 msg.message_id = id;
631 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100632 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
633 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100634 // If this message queue processes 1 message every millisecond for 50 days,
635 // we will wrap this number. Even then, only messages with identical times
636 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100637 ++delayed_next_num_;
638 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100639 }
640 WakeUpSocketServer();
641}
642
643int Thread::GetDelay() {
644 CritScope cs(&crit_);
645
Sebastian Jansson61380c02020-01-17 14:46:08 +0100646 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100647 return 0;
648
Sebastian Jansson61380c02020-01-17 14:46:08 +0100649 if (!delayed_messages_.empty()) {
650 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100651 if (delay < 0)
652 delay = 0;
653 return delay;
654 }
655
656 return kForever;
657}
658
659void Thread::ClearInternal(MessageHandler* phandler,
660 uint32_t id,
661 MessageList* removed) {
662 // Remove messages with phandler
663
664 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
665 if (removed) {
666 removed->push_back(msgPeek_);
667 } else {
668 delete msgPeek_.pdata;
669 }
670 fPeekKeep_ = false;
671 }
672
673 // Remove from ordered message queue
674
Sebastian Jansson61380c02020-01-17 14:46:08 +0100675 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100676 if (it->Match(phandler, id)) {
677 if (removed) {
678 removed->push_back(*it);
679 } else {
680 delete it->pdata;
681 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100682 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100683 } else {
684 ++it;
685 }
686 }
687
688 // Remove from priority queue. Not directly iterable, so use this approach
689
Sebastian Jansson61380c02020-01-17 14:46:08 +0100690 auto new_end = delayed_messages_.container().begin();
691 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100692 if (it->msg_.Match(phandler, id)) {
693 if (removed) {
694 removed->push_back(it->msg_);
695 } else {
696 delete it->msg_.pdata;
697 }
698 } else {
699 *new_end++ = *it;
700 }
701 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100702 delayed_messages_.container().erase(new_end,
703 delayed_messages_.container().end());
704 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100705}
706
707void Thread::Dispatch(Message* pmsg) {
708 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
709 pmsg->posted_from.file_name(), "src_func",
710 pmsg->posted_from.function_name());
Harald Alvestrandba694422021-01-27 21:52:14 +0000711 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100712 int64_t start_time = TimeMillis();
713 pmsg->phandler->OnMessage(pmsg);
714 int64_t end_time = TimeMillis();
715 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000716 if (diff >= dispatch_warning_ms_) {
717 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100718 << "ms to dispatch. Posted from: "
719 << pmsg->posted_from.ToString();
Harald Alvestrandba694422021-01-27 21:52:14 +0000720 // To avoid log spew, move the warning limit to only give warning
721 // for delays that are larger than the one observed.
722 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100723 }
724}
725
nisse7866cfe2017-04-26 01:45:31 -0700726bool Thread::IsCurrent() const {
727 return ThreadManager::Instance()->CurrentThread() == this;
728}
729
danilchapbebf54c2016-04-28 01:32:48 -0700730std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100731 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700732}
733
734std::unique_ptr<Thread> Thread::Create() {
735 return std::unique_ptr<Thread>(
736 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
737}
738
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000739bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000740 AssertBlockingIsAllowedOnCurrentThread();
741
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000742#if defined(WEBRTC_WIN)
743 ::Sleep(milliseconds);
744 return true;
745#else
746 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
747 // so we use nanosleep() even though it has greater precision than necessary.
748 struct timespec ts;
749 ts.tv_sec = milliseconds / 1000;
750 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800751 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000752 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100753 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000754 return false;
755 }
756 return true;
757#endif
758}
759
760bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100761 RTC_DCHECK(!IsRunning());
762
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000763 name_ = name;
764 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200765 // The %p specifier typically produce at most 16 hex digits, possibly with a
766 // 0x prefix. But format is implementation defined, so add some margin.
767 char buf[30];
768 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000769 name_ += buf;
770 }
771 return true;
772}
773
Harald Alvestrandba694422021-01-27 21:52:14 +0000774void Thread::SetDispatchWarningMs(int deadline) {
775 if (!IsCurrent()) {
776 PostTask(webrtc::ToQueuedTask(
777 [this, deadline]() { SetDispatchWarningMs(deadline); }));
778 return;
779 }
780 RTC_DCHECK_RUN_ON(this);
781 dispatch_warning_ms_ = deadline;
782}
783
Niels Möllerd2e50132019-06-11 09:24:14 +0200784bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100785 RTC_DCHECK(!IsRunning());
786
787 if (IsRunning())
788 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000789
André Susano Pinto02a57972016-07-22 13:30:05 +0200790 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000791
792 // Make sure that ThreadManager is created on the main thread before
793 // we start a new thread.
794 ThreadManager::Instance();
795
Tommi51492422017-12-04 15:18:23 +0100796 owned_ = true;
797
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000798#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200799 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100800 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000801 return false;
802 }
803#elif defined(WEBRTC_POSIX)
804 pthread_attr_t attr;
805 pthread_attr_init(&attr);
806
Niels Möllerd2e50132019-06-11 09:24:14 +0200807 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000808 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100809 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100810 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000811 return false;
812 }
Tommi51492422017-12-04 15:18:23 +0100813 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000814#endif
815 return true;
816}
817
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000818bool Thread::WrapCurrent() {
819 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
820}
821
822void Thread::UnwrapCurrent() {
823 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800824 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000825#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800826 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000827 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100828 RTC_LOG_GLE(LS_ERROR)
829 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000830 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800831 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100832 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000833 }
Tommi51492422017-12-04 15:18:23 +0100834#elif defined(WEBRTC_POSIX)
835 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000836#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000837}
838
839void Thread::SafeWrapCurrent() {
840 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
841}
842
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000843void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100844 if (!IsRunning())
845 return;
846
847 RTC_DCHECK(!IsCurrent());
848 if (Current() && !Current()->blocking_calls_allowed_) {
849 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100850 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100851 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000852
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000853#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100854 RTC_DCHECK(thread_ != nullptr);
855 WaitForSingleObject(thread_, INFINITE);
856 CloseHandle(thread_);
857 thread_ = nullptr;
858 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000859#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100860 pthread_join(thread_, nullptr);
861 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000862#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000863}
864
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000865bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800866 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000867 bool previous = blocking_calls_allowed_;
868 blocking_calls_allowed_ = allow;
869 return previous;
870}
871
872// static
873void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700874#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000875 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800876 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000877#endif
878}
879
deadbeefdc20e262017-01-31 15:10:44 -0800880// static
881#if defined(WEBRTC_WIN)
882DWORD WINAPI Thread::PreRun(LPVOID pv) {
883#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000884void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800885#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200886 Thread* thread = static_cast<Thread*>(pv);
887 ThreadManager::Instance()->SetCurrentThread(thread);
888 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200889#if defined(WEBRTC_MAC)
890 ScopedAutoReleasePool pool;
891#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200892 thread->Run();
893
Tommi51492422017-12-04 15:18:23 +0100894 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800895#ifdef WEBRTC_WIN
896 return 0;
897#else
898 return nullptr;
899#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200900} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000901
902void Thread::Run() {
903 ProcessMessages(kForever);
904}
905
906bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100907 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000908 return owned_;
909}
910
911void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100912 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000913 Join();
914}
915
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700916void Thread::Send(const Location& posted_from,
917 MessageHandler* phandler,
918 uint32_t id,
919 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100920 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200921 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000922 return;
923
924 // Sent messages are sent to the MessageHandler directly, in the context
925 // of "thread", like Win32 SendMessage. If in the right context,
926 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000927 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700928 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000929 msg.phandler = phandler;
930 msg.message_id = id;
931 msg.pdata = pdata;
932 if (IsCurrent()) {
Tommife041642021-04-07 10:08:28 +0200933#if RTC_DCHECK_IS_ON
934 RTC_DCHECK_RUN_ON(this);
935 could_be_blocking_call_count_++;
936#endif
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100937 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000938 return;
939 }
940
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000941 AssertBlockingIsAllowedOnCurrentThread();
942
Yves Gerey665174f2018-06-19 15:03:05 +0200943 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200944
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100945#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200946 if (current_thread) {
Tommife041642021-04-07 10:08:28 +0200947 RTC_DCHECK_RUN_ON(current_thread);
948 current_thread->blocking_call_count_++;
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200949 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
950 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
951 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000952 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200953#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000954
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200955 // Perhaps down the line we can get rid of this workaround and always require
956 // current_thread to be valid when Send() is called.
957 std::unique_ptr<rtc::Event> done_event;
958 if (!current_thread)
959 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000960
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200961 bool ready = false;
962 PostTask(webrtc::ToQueuedTask(
963 [&msg]() mutable { msg.phandler->OnMessage(&msg); },
964 [this, &ready, current_thread, done = done_event.get()] {
965 if (current_thread) {
966 CritScope cs(&crit_);
967 ready = true;
968 current_thread->socketserver()->WakeUp();
969 } else {
970 done->Set();
971 }
972 }));
973
974 if (current_thread) {
975 bool waited = false;
976 crit_.Enter();
977 while (!ready) {
978 crit_.Leave();
979 current_thread->socketserver()->Wait(kForever, false);
980 waited = true;
981 crit_.Enter();
982 }
983 crit_.Leave();
984
985 // Our Wait loop above may have consumed some WakeUp events for this
986 // Thread, that weren't relevant to this Send. Losing these WakeUps can
987 // cause problems for some SocketServers.
988 //
989 // Concrete example:
990 // Win32SocketServer on thread A calls Send on thread B. While processing
991 // the message, thread B Posts a message to A. We consume the wakeup for
992 // that Post while waiting for the Send to complete, which means that when
993 // we exit this loop, we need to issue another WakeUp, or else the Posted
994 // message won't be processed in a timely manner.
995
996 if (waited) {
997 current_thread->socketserver()->WakeUp();
998 }
999 } else {
1000 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001001 }
1002}
1003
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001004void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +01001005 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -08001006 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
1007 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +01001008
1009 class FunctorMessageHandler : public MessageHandler {
1010 public:
1011 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +02001012 : functor_(functor) {}
Danil Chapovalov89313452019-11-29 12:56:43 +01001013 void OnMessage(Message* msg) override { functor_(); }
1014
1015 private:
1016 rtc::FunctionView<void()> functor_;
1017 } handler(functor);
1018
1019 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +00001020}
1021
Tommi6866dc72020-05-15 10:11:56 +02001022// Called by the ThreadManager when being set as the current thread.
1023void Thread::EnsureIsCurrentTaskQueue() {
1024 task_queue_registration_ =
1025 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
1026}
1027
1028// Called by the ThreadManager when being set as the current thread.
1029void Thread::ClearCurrentTaskQueue() {
1030 task_queue_registration_.reset();
1031}
1032
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001033void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
1034 RTC_DCHECK(msg);
1035 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
1036 std::unique_ptr<webrtc::QueuedTask> task = std::move(data->data());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001037 // Thread expects handler to own Message::pdata when OnMessage is called
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001038 // Since MessageData is no longer needed, delete it.
1039 delete data;
1040
1041 // QueuedTask interface uses Run return value to communicate who owns the
1042 // task. false means QueuedTask took the ownership.
1043 if (!task->Run())
1044 task.release();
1045}
1046
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001047void Thread::AllowInvokesToThread(Thread* thread) {
1048#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1049 if (!IsCurrent()) {
1050 PostTask(webrtc::ToQueuedTask(
1051 [thread, this]() { AllowInvokesToThread(thread); }));
1052 return;
1053 }
1054 RTC_DCHECK_RUN_ON(this);
1055 allowed_threads_.push_back(thread);
1056 invoke_policy_enabled_ = true;
1057#endif
1058}
1059
1060void Thread::DisallowAllInvokes() {
1061#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1062 if (!IsCurrent()) {
1063 PostTask(webrtc::ToQueuedTask([this]() { DisallowAllInvokes(); }));
1064 return;
1065 }
1066 RTC_DCHECK_RUN_ON(this);
1067 allowed_threads_.clear();
1068 invoke_policy_enabled_ = true;
1069#endif
1070}
1071
Tommife041642021-04-07 10:08:28 +02001072#if RTC_DCHECK_IS_ON
1073uint32_t Thread::GetBlockingCallCount() const {
1074 RTC_DCHECK_RUN_ON(this);
1075 return blocking_call_count_;
1076}
1077uint32_t Thread::GetCouldBeBlockingCallCount() const {
1078 RTC_DCHECK_RUN_ON(this);
1079 return could_be_blocking_call_count_;
1080}
1081#endif
1082
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001083// Returns true if no policies added or if there is at least one policy
1084// that permits invocation to |target| thread.
1085bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
1086#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1087 RTC_DCHECK_RUN_ON(this);
1088 if (!invoke_policy_enabled_) {
1089 return true;
1090 }
1091 for (const auto* thread : allowed_threads_) {
1092 if (thread == target) {
1093 return true;
1094 }
1095 }
1096 return false;
1097#else
1098 return true;
1099#endif
1100}
1101
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001102void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
1103 // Though Post takes MessageData by raw pointer (last parameter), it still
1104 // takes it with ownership.
1105 Post(RTC_FROM_HERE, &queued_task_handler_,
1106 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1107}
1108
1109void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
1110 uint32_t milliseconds) {
1111 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1112 // it still takes it with ownership.
1113 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
1114 /*id=*/0,
1115 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1116}
1117
1118void Thread::Delete() {
1119 Stop();
1120 delete this;
1121}
1122
Niels Möller8909a632018-09-06 08:42:44 +02001123bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001124 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001125}
1126
Peter Boström0c4e06b2015-10-07 12:23:21 +02001127void Thread::Clear(MessageHandler* phandler,
1128 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001129 MessageList* removed) {
1130 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001131 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001132}
1133
1134bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001135 // Using ProcessMessages with a custom clock for testing and a time greater
1136 // than 0 doesn't work, since it's not guaranteed to advance the custom
1137 // clock's time, and may get stuck in an infinite loop.
1138 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1139 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001140 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001141 int cmsNext = cmsLoop;
1142
1143 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001144#if defined(WEBRTC_MAC)
1145 ScopedAutoReleasePool pool;
1146#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001147 Message msg;
1148 if (!Get(&msg, cmsNext))
1149 return !IsQuitting();
1150 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001151
kthelgasonde6adbe2017-02-22 00:42:11 -08001152 if (cmsLoop != kForever) {
1153 cmsNext = static_cast<int>(TimeUntil(msEnd));
1154 if (cmsNext < 0)
1155 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001156 }
1157 }
1158}
1159
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001160bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1161 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001162 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001163
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001164#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001165 if (need_synchronize_access) {
1166 // We explicitly ask for no rights other than synchronization.
1167 // This gives us the best chance of succeeding.
1168 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1169 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001170 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001171 return false;
1172 }
1173 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001174 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001175#elif defined(WEBRTC_POSIX)
1176 thread_ = pthread_self();
1177#endif
1178 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001179 thread_manager->SetCurrentThread(this);
1180 return true;
1181}
1182
Tommi51492422017-12-04 15:18:23 +01001183bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001184#if defined(WEBRTC_WIN)
1185 return thread_ != nullptr;
1186#elif defined(WEBRTC_POSIX)
1187 return thread_ != 0;
1188#endif
1189}
1190
Steve Antonbcc1a762019-12-11 11:21:53 -08001191// static
1192MessageHandler* Thread::GetPostTaskMessageHandler() {
1193 // Allocate at first call, never deallocate.
1194 static MessageHandler* handler = new MessageHandlerWithTask;
1195 return handler;
1196}
1197
Taylor Brandstetter08672602018-03-02 15:20:33 -08001198AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +01001199 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001200 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001201 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001202 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1203 // post a message to a queue that no running thread is serving.
1204 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001205 ThreadManager::Instance()->SetCurrentThread(this);
1206 }
1207}
1208
1209AutoThread::~AutoThread() {
1210 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001211 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001212 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001213 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001214 }
1215}
1216
nisse7eaa4ea2017-05-08 05:25:41 -07001217AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001218 : Thread(ss, /*do_init=*/false) {
1219 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001220 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001221 // Temporarily set the current thread to nullptr so that we can keep checks
1222 // around that catch unintentional pointer overwrites.
1223 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001224 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1225 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001226 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001227 }
1228}
1229
1230AutoSocketServerThread::~AutoSocketServerThread() {
1231 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
1232 // Some tests post destroy messages to this thread. To avoid memory
1233 // leaks, we have to process those messages. In particular
1234 // P2PTransportChannelPingTest, relying on the message posted in
1235 // cricket::Connection::Destroy.
1236 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -07001237 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001238 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001239 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1240 // its contents rely on this thread still being set as the current thread.
1241 Stop();
1242 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001243 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001244 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1245 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001246 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001247 }
1248}
1249
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001250} // namespace rtc