blob: 307d49925500a3761c360bc6e47e60281a19fe02 [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
Byoungchan Lee14af7622022-01-12 05:24:58 +090078 MessageHandlerWithTask(const MessageHandlerWithTask&) = delete;
79 MessageHandlerWithTask& operator=(const MessageHandlerWithTask&) = delete;
80
Steve Antonbcc1a762019-12-11 11:21:53 -080081 void OnMessage(Message* msg) override {
82 static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
83 delete msg->pdata;
84 }
85
86 private:
87 ~MessageHandlerWithTask() override {}
Steve Antonbcc1a762019-12-11 11:21:53 -080088};
89
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010090class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
91 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020092 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
93 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010094 : cs_(cs), processing_(processing) {
95 cs_->Enter();
96 *processing_ += 1;
97 }
98
99 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
100 *processing_ -= 1;
101 cs_->Leave();
102 }
103
Byoungchan Lee14af7622022-01-12 05:24:58 +0900104 MarkProcessingCritScope(const MarkProcessingCritScope&) = delete;
105 MarkProcessingCritScope& operator=(const MarkProcessingCritScope&) = delete;
106
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100107 private:
Markus Handell3cb525b2020-07-16 16:16:09 +0200108 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100109 size_t* processing_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100110};
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.
Artem Titovd3251962021-11-15 16:57:07 +0100121 RTC_DCHECK_NOTREACHED() << "ThreadManager should never be destructed.";
nisse7866cfe2017-04-26 01:45:31 -0700122}
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
nisse7866cfe2017-04-26 01:45:31 -0700258 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000259}
260
261#if defined(WEBRTC_POSIX)
Niels Möller98d26df2022-02-07 10:35:29 +0100262ThreadManager::ThreadManager() {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200263#if defined(WEBRTC_MAC)
264 InitCocoaMultiThreading();
265#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800266 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267}
268
Yves Gerey665174f2018-06-19 15:03:05 +0200269Thread* ThreadManager::CurrentThread() {
270 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271}
272
Sebastian Jansson178a6852020-01-14 11:12:26 +0100273void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000274 pthread_setspecific(key_, thread);
275}
276#endif
277
278#if defined(WEBRTC_WIN)
Niels Möller98d26df2022-02-07 10:35:29 +0100279ThreadManager::ThreadManager() : key_(TlsAlloc()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200280
281Thread* ThreadManager::CurrentThread() {
282 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000283}
284
Sebastian Jansson178a6852020-01-14 11:12:26 +0100285void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286 TlsSetValue(key_, thread);
287}
288#endif
289
Sebastian Jansson178a6852020-01-14 11:12:26 +0100290void ThreadManager::SetCurrentThread(Thread* thread) {
291#if RTC_DLOG_IS_ON
292 if (CurrentThread() && thread) {
293 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
294 }
295#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200296
297 if (thread) {
298 thread->EnsureIsCurrentTaskQueue();
299 } else {
300 Thread* current = CurrentThread();
301 if (current) {
302 // The current thread is being cleared, e.g. as a result of
303 // UnwrapCurrent() being called or when a thread is being stopped
304 // (see PreRun()). This signals that the Thread instance is being detached
305 // from the thread, which also means that TaskQueue::Current() must not
306 // return a pointer to the Thread instance.
307 current->ClearCurrentTaskQueue();
308 }
309 }
310
Sebastian Jansson178a6852020-01-14 11:12:26 +0100311 SetCurrentThreadInternal(thread);
312}
313
314void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
315 SetCurrentThreadInternal(thread);
316}
317
Yves Gerey665174f2018-06-19 15:03:05 +0200318Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000319 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800320 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100321 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000322 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323 }
324 return result;
325}
326
327void ThreadManager::UnwrapCurrentThread() {
328 Thread* t = CurrentThread();
329 if (t && !(t->IsOwned())) {
330 t->UnwrapCurrent();
331 delete t;
332 }
333}
334
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000335Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200336 : thread_(Thread::Current()),
337 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000338
339Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800340 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000341 thread_->SetAllowBlockingCalls(previous_state_);
342}
343
Tommife041642021-04-07 10:08:28 +0200344#if RTC_DCHECK_IS_ON
345Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls(
346 std::function<void(uint32_t, uint32_t)> callback)
347 : thread_(Thread::Current()),
348 base_blocking_call_count_(thread_->GetBlockingCallCount()),
349 base_could_be_blocking_call_count_(
350 thread_->GetCouldBeBlockingCallCount()),
351 result_callback_(std::move(callback)) {}
352
353Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() {
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200354 if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) {
355 result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount());
356 }
Tommife041642021-04-07 10:08:28 +0200357}
358
359uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const {
360 return thread_->GetBlockingCallCount() - base_blocking_call_count_;
361}
362
363uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const {
364 return thread_->GetCouldBeBlockingCallCount() -
365 base_could_be_blocking_call_count_;
366}
367
368uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const {
369 return GetBlockingCallCount() + GetCouldBeBlockingCallCount();
370}
371#endif
372
Taylor Brandstetter08672602018-03-02 15:20:33 -0800373Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700374
375Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800376 : Thread(std::move(ss), /*do_init=*/true) {}
377
378Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100379 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100380 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100381 fInitialized_(false),
382 fDestroyed_(false),
383 stop_(0),
384 ss_(ss) {
385 RTC_DCHECK(ss);
386 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800387 SetName("Thread", this); // default name
388 if (do_init) {
389 DoInit();
390 }
391}
392
393Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100394 : Thread(ss.get(), do_init) {
395 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000396}
397
398Thread::~Thread() {
399 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800400 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000401}
402
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100403void Thread::DoInit() {
404 if (fInitialized_) {
405 return;
406 }
407
408 fInitialized_ = true;
409 ThreadManager::Add(this);
410}
411
412void Thread::DoDestroy() {
413 if (fDestroyed_) {
414 return;
415 }
416
417 fDestroyed_ = true;
418 // The signal is done from here to ensure
419 // that it always gets called when the queue
420 // is going away.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100421 if (ss_) {
422 ss_->SetMessageQueue(nullptr);
423 }
Niels Möller9bd24572021-04-19 12:18:27 +0200424 ThreadManager::Remove(this);
425 ClearInternal(nullptr, MQID_ANY, nullptr);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100426}
427
428SocketServer* Thread::socketserver() {
429 return ss_;
430}
431
432void Thread::WakeUpSocketServer() {
433 ss_->WakeUp();
434}
435
436void Thread::Quit() {
437 AtomicOps::ReleaseStore(&stop_, 1);
438 WakeUpSocketServer();
439}
440
441bool Thread::IsQuitting() {
442 return AtomicOps::AcquireLoad(&stop_) != 0;
443}
444
445void Thread::Restart() {
446 AtomicOps::ReleaseStore(&stop_, 0);
447}
448
449bool Thread::Peek(Message* pmsg, int cmsWait) {
450 if (fPeekKeep_) {
451 *pmsg = msgPeek_;
452 return true;
453 }
454 if (!Get(pmsg, cmsWait))
455 return false;
456 msgPeek_ = *pmsg;
457 fPeekKeep_ = true;
458 return true;
459}
460
461bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
462 // Return and clear peek if present
463 // Always return the peek if it exists so there is Peek/Get symmetry
464
465 if (fPeekKeep_) {
466 *pmsg = msgPeek_;
467 fPeekKeep_ = false;
468 return true;
469 }
470
471 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
472
473 int64_t cmsTotal = cmsWait;
474 int64_t cmsElapsed = 0;
475 int64_t msStart = TimeMillis();
476 int64_t msCurrent = msStart;
477 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100478 // Check for posted events
479 int64_t cmsDelayNext = kForever;
480 bool first_pass = true;
481 while (true) {
482 // All queue operations need to be locked, but nothing else in this loop
483 // (specifically handling disposed message) can happen inside the crit.
484 // Otherwise, disposed MessageHandlers will cause deadlocks.
485 {
486 CritScope cs(&crit_);
487 // On the first pass, check for delayed messages that have been
488 // triggered and calculate the next trigger time.
489 if (first_pass) {
490 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100491 while (!delayed_messages_.empty()) {
492 if (msCurrent < delayed_messages_.top().run_time_ms_) {
493 cmsDelayNext =
494 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100495 break;
496 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100497 messages_.push_back(delayed_messages_.top().msg_);
498 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100499 }
500 }
501 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100502 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100503 break;
504 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100505 *pmsg = messages_.front();
506 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100507 }
508 } // crit_ is released here.
509
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100510 // If this was a dispose message, delete it and skip it.
511 if (MQID_DISPOSE == pmsg->message_id) {
512 RTC_DCHECK(nullptr == pmsg->phandler);
513 delete pmsg->pdata;
514 *pmsg = Message();
515 continue;
516 }
517 return true;
518 }
519
520 if (IsQuitting())
521 break;
522
523 // Which is shorter, the delay wait or the asked wait?
524
525 int64_t cmsNext;
526 if (cmsWait == kForever) {
527 cmsNext = cmsDelayNext;
528 } else {
529 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
530 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
531 cmsNext = cmsDelayNext;
532 }
533
534 {
535 // Wait and multiplex in the meantime
536 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
537 return false;
538 }
539
540 // If the specified timeout expired, return
541
542 msCurrent = TimeMillis();
543 cmsElapsed = TimeDiff(msCurrent, msStart);
544 if (cmsWait != kForever) {
545 if (cmsElapsed >= cmsWait)
546 return false;
547 }
548 }
549 return false;
550}
551
552void Thread::Post(const Location& posted_from,
553 MessageHandler* phandler,
554 uint32_t id,
555 MessageData* pdata,
556 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100557 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100558 if (IsQuitting()) {
559 delete pdata;
560 return;
561 }
562
563 // Keep thread safe
564 // Add the message to the end of the queue
565 // Signal for the multiplexer to return
566
567 {
568 CritScope cs(&crit_);
569 Message msg;
570 msg.posted_from = posted_from;
571 msg.phandler = phandler;
572 msg.message_id = id;
573 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100574 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100575 }
576 WakeUpSocketServer();
577}
578
579void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100580 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100581 MessageHandler* phandler,
582 uint32_t id,
583 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100584 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100585 pdata);
586}
587
588void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100589 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100590 MessageHandler* phandler,
591 uint32_t id,
592 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100593 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100594 pdata);
595}
596
597void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100598 int64_t delay_ms,
599 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100600 MessageHandler* phandler,
601 uint32_t id,
602 MessageData* pdata) {
603 if (IsQuitting()) {
604 delete pdata;
605 return;
606 }
607
608 // Keep thread safe
609 // Add to the priority queue. Gets sorted soonest first.
610 // Signal for the multiplexer to return.
611
612 {
613 CritScope cs(&crit_);
614 Message msg;
615 msg.posted_from = posted_from;
616 msg.phandler = phandler;
617 msg.message_id = id;
618 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100619 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
620 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100621 // If this message queue processes 1 message every millisecond for 50 days,
622 // we will wrap this number. Even then, only messages with identical times
623 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100624 ++delayed_next_num_;
625 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100626 }
627 WakeUpSocketServer();
628}
629
630int Thread::GetDelay() {
631 CritScope cs(&crit_);
632
Sebastian Jansson61380c02020-01-17 14:46:08 +0100633 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100634 return 0;
635
Sebastian Jansson61380c02020-01-17 14:46:08 +0100636 if (!delayed_messages_.empty()) {
637 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100638 if (delay < 0)
639 delay = 0;
640 return delay;
641 }
642
643 return kForever;
644}
645
646void Thread::ClearInternal(MessageHandler* phandler,
647 uint32_t id,
648 MessageList* removed) {
649 // Remove messages with phandler
650
651 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
652 if (removed) {
653 removed->push_back(msgPeek_);
654 } else {
655 delete msgPeek_.pdata;
656 }
657 fPeekKeep_ = false;
658 }
659
660 // Remove from ordered message queue
661
Sebastian Jansson61380c02020-01-17 14:46:08 +0100662 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100663 if (it->Match(phandler, id)) {
664 if (removed) {
665 removed->push_back(*it);
666 } else {
667 delete it->pdata;
668 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100669 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100670 } else {
671 ++it;
672 }
673 }
674
675 // Remove from priority queue. Not directly iterable, so use this approach
676
Sebastian Jansson61380c02020-01-17 14:46:08 +0100677 auto new_end = delayed_messages_.container().begin();
678 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100679 if (it->msg_.Match(phandler, id)) {
680 if (removed) {
681 removed->push_back(it->msg_);
682 } else {
683 delete it->msg_.pdata;
684 }
685 } else {
686 *new_end++ = *it;
687 }
688 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100689 delayed_messages_.container().erase(new_end,
690 delayed_messages_.container().end());
691 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100692}
693
694void Thread::Dispatch(Message* pmsg) {
695 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
696 pmsg->posted_from.file_name(), "src_func",
697 pmsg->posted_from.function_name());
Harald Alvestrandba694422021-01-27 21:52:14 +0000698 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100699 int64_t start_time = TimeMillis();
700 pmsg->phandler->OnMessage(pmsg);
701 int64_t end_time = TimeMillis();
702 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000703 if (diff >= dispatch_warning_ms_) {
704 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100705 << "ms to dispatch. Posted from: "
706 << pmsg->posted_from.ToString();
Harald Alvestrandba694422021-01-27 21:52:14 +0000707 // To avoid log spew, move the warning limit to only give warning
708 // for delays that are larger than the one observed.
709 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100710 }
711}
712
nisse7866cfe2017-04-26 01:45:31 -0700713bool Thread::IsCurrent() const {
714 return ThreadManager::Instance()->CurrentThread() == this;
715}
716
danilchapbebf54c2016-04-28 01:32:48 -0700717std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100718 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700719}
720
721std::unique_ptr<Thread> Thread::Create() {
722 return std::unique_ptr<Thread>(
723 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
724}
725
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000726bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000727 AssertBlockingIsAllowedOnCurrentThread();
728
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000729#if defined(WEBRTC_WIN)
730 ::Sleep(milliseconds);
731 return true;
732#else
733 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
734 // so we use nanosleep() even though it has greater precision than necessary.
735 struct timespec ts;
736 ts.tv_sec = milliseconds / 1000;
737 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800738 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000739 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100740 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000741 return false;
742 }
743 return true;
744#endif
745}
746
747bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100748 RTC_DCHECK(!IsRunning());
749
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000750 name_ = name;
751 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200752 // The %p specifier typically produce at most 16 hex digits, possibly with a
753 // 0x prefix. But format is implementation defined, so add some margin.
754 char buf[30];
755 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000756 name_ += buf;
757 }
758 return true;
759}
760
Harald Alvestrandba694422021-01-27 21:52:14 +0000761void Thread::SetDispatchWarningMs(int deadline) {
762 if (!IsCurrent()) {
763 PostTask(webrtc::ToQueuedTask(
764 [this, deadline]() { SetDispatchWarningMs(deadline); }));
765 return;
766 }
767 RTC_DCHECK_RUN_ON(this);
768 dispatch_warning_ms_ = deadline;
769}
770
Niels Möllerd2e50132019-06-11 09:24:14 +0200771bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100772 RTC_DCHECK(!IsRunning());
773
774 if (IsRunning())
775 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000776
André Susano Pinto02a57972016-07-22 13:30:05 +0200777 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000778
779 // Make sure that ThreadManager is created on the main thread before
780 // we start a new thread.
781 ThreadManager::Instance();
782
Tommi51492422017-12-04 15:18:23 +0100783 owned_ = true;
784
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000785#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200786 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100787 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000788 return false;
789 }
790#elif defined(WEBRTC_POSIX)
791 pthread_attr_t attr;
792 pthread_attr_init(&attr);
793
Niels Möllerd2e50132019-06-11 09:24:14 +0200794 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000795 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100796 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100797 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000798 return false;
799 }
Tommi51492422017-12-04 15:18:23 +0100800 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000801#endif
802 return true;
803}
804
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000805bool Thread::WrapCurrent() {
806 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
807}
808
809void Thread::UnwrapCurrent() {
810 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800811 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000812#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800813 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000814 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100815 RTC_LOG_GLE(LS_ERROR)
816 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000817 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800818 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100819 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000820 }
Tommi51492422017-12-04 15:18:23 +0100821#elif defined(WEBRTC_POSIX)
822 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000823#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000824}
825
826void Thread::SafeWrapCurrent() {
827 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
828}
829
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000830void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100831 if (!IsRunning())
832 return;
833
834 RTC_DCHECK(!IsCurrent());
835 if (Current() && !Current()->blocking_calls_allowed_) {
836 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100837 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100838 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000839
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000840#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100841 RTC_DCHECK(thread_ != nullptr);
842 WaitForSingleObject(thread_, INFINITE);
843 CloseHandle(thread_);
844 thread_ = nullptr;
845 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000846#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100847 pthread_join(thread_, nullptr);
848 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000849#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000850}
851
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000852bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800853 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000854 bool previous = blocking_calls_allowed_;
855 blocking_calls_allowed_ = allow;
856 return previous;
857}
858
859// static
860void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700861#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000862 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800863 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000864#endif
865}
866
deadbeefdc20e262017-01-31 15:10:44 -0800867// static
868#if defined(WEBRTC_WIN)
869DWORD WINAPI Thread::PreRun(LPVOID pv) {
870#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000871void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800872#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200873 Thread* thread = static_cast<Thread*>(pv);
874 ThreadManager::Instance()->SetCurrentThread(thread);
875 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200876#if defined(WEBRTC_MAC)
877 ScopedAutoReleasePool pool;
878#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200879 thread->Run();
880
Tommi51492422017-12-04 15:18:23 +0100881 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800882#ifdef WEBRTC_WIN
883 return 0;
884#else
885 return nullptr;
886#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200887} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000888
889void Thread::Run() {
890 ProcessMessages(kForever);
891}
892
893bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100894 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000895 return owned_;
896}
897
898void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100899 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000900 Join();
901}
902
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700903void Thread::Send(const Location& posted_from,
904 MessageHandler* phandler,
905 uint32_t id,
906 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100907 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200908 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000909 return;
910
911 // Sent messages are sent to the MessageHandler directly, in the context
912 // of "thread", like Win32 SendMessage. If in the right context,
913 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000914 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700915 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000916 msg.phandler = phandler;
917 msg.message_id = id;
918 msg.pdata = pdata;
919 if (IsCurrent()) {
Tommife041642021-04-07 10:08:28 +0200920#if RTC_DCHECK_IS_ON
Artem Titov15737162021-05-25 11:17:07 +0200921 RTC_DCHECK(this->IsInvokeToThreadAllowed(this));
Tommife041642021-04-07 10:08:28 +0200922 RTC_DCHECK_RUN_ON(this);
923 could_be_blocking_call_count_++;
924#endif
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100925 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000926 return;
927 }
928
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000929 AssertBlockingIsAllowedOnCurrentThread();
930
Yves Gerey665174f2018-06-19 15:03:05 +0200931 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200932
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100933#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200934 if (current_thread) {
Tommife041642021-04-07 10:08:28 +0200935 RTC_DCHECK_RUN_ON(current_thread);
936 current_thread->blocking_call_count_++;
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200937 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
938 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
939 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000940 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200941#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000942
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200943 // Perhaps down the line we can get rid of this workaround and always require
944 // current_thread to be valid when Send() is called.
945 std::unique_ptr<rtc::Event> done_event;
946 if (!current_thread)
947 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000948
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200949 bool ready = false;
950 PostTask(webrtc::ToQueuedTask(
951 [&msg]() mutable { msg.phandler->OnMessage(&msg); },
952 [this, &ready, current_thread, done = done_event.get()] {
953 if (current_thread) {
954 CritScope cs(&crit_);
955 ready = true;
956 current_thread->socketserver()->WakeUp();
957 } else {
958 done->Set();
959 }
960 }));
961
962 if (current_thread) {
963 bool waited = false;
964 crit_.Enter();
965 while (!ready) {
966 crit_.Leave();
967 current_thread->socketserver()->Wait(kForever, false);
968 waited = true;
969 crit_.Enter();
970 }
971 crit_.Leave();
972
973 // Our Wait loop above may have consumed some WakeUp events for this
974 // Thread, that weren't relevant to this Send. Losing these WakeUps can
975 // cause problems for some SocketServers.
976 //
977 // Concrete example:
978 // Win32SocketServer on thread A calls Send on thread B. While processing
979 // the message, thread B Posts a message to A. We consume the wakeup for
980 // that Post while waiting for the Send to complete, which means that when
981 // we exit this loop, we need to issue another WakeUp, or else the Posted
982 // message won't be processed in a timely manner.
983
984 if (waited) {
985 current_thread->socketserver()->WakeUp();
986 }
987 } else {
988 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000989 }
990}
991
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700992void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100993 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800994 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
995 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100996
997 class FunctorMessageHandler : public MessageHandler {
998 public:
999 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +02001000 : functor_(functor) {}
Danil Chapovalov89313452019-11-29 12:56:43 +01001001 void OnMessage(Message* msg) override { functor_(); }
1002
1003 private:
1004 rtc::FunctionView<void()> functor_;
1005 } handler(functor);
1006
1007 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +00001008}
1009
Tommi6866dc72020-05-15 10:11:56 +02001010// Called by the ThreadManager when being set as the current thread.
1011void Thread::EnsureIsCurrentTaskQueue() {
1012 task_queue_registration_ =
1013 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
1014}
1015
1016// Called by the ThreadManager when being set as the current thread.
1017void Thread::ClearCurrentTaskQueue() {
1018 task_queue_registration_.reset();
1019}
1020
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001021void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
1022 RTC_DCHECK(msg);
1023 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
Mirko Bonadei179b46b2021-07-24 21:50:24 +02001024 std::unique_ptr<webrtc::QueuedTask> task(data->Release());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001025 // Thread expects handler to own Message::pdata when OnMessage is called
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001026 // Since MessageData is no longer needed, delete it.
1027 delete data;
1028
1029 // QueuedTask interface uses Run return value to communicate who owns the
1030 // task. false means QueuedTask took the ownership.
1031 if (!task->Run())
1032 task.release();
1033}
1034
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001035void Thread::AllowInvokesToThread(Thread* thread) {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001036#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001037 if (!IsCurrent()) {
1038 PostTask(webrtc::ToQueuedTask(
1039 [thread, this]() { AllowInvokesToThread(thread); }));
1040 return;
1041 }
1042 RTC_DCHECK_RUN_ON(this);
1043 allowed_threads_.push_back(thread);
1044 invoke_policy_enabled_ = true;
1045#endif
1046}
1047
1048void Thread::DisallowAllInvokes() {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001049#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001050 if (!IsCurrent()) {
1051 PostTask(webrtc::ToQueuedTask([this]() { DisallowAllInvokes(); }));
1052 return;
1053 }
1054 RTC_DCHECK_RUN_ON(this);
1055 allowed_threads_.clear();
1056 invoke_policy_enabled_ = true;
1057#endif
1058}
1059
Tommife041642021-04-07 10:08:28 +02001060#if RTC_DCHECK_IS_ON
1061uint32_t Thread::GetBlockingCallCount() const {
1062 RTC_DCHECK_RUN_ON(this);
1063 return blocking_call_count_;
1064}
1065uint32_t Thread::GetCouldBeBlockingCallCount() const {
1066 RTC_DCHECK_RUN_ON(this);
1067 return could_be_blocking_call_count_;
1068}
1069#endif
1070
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001071// Returns true if no policies added or if there is at least one policy
Artem Titov96e3b992021-07-26 16:03:14 +02001072// that permits invocation to `target` thread.
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001073bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001074#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001075 RTC_DCHECK_RUN_ON(this);
1076 if (!invoke_policy_enabled_) {
1077 return true;
1078 }
1079 for (const auto* thread : allowed_threads_) {
1080 if (thread == target) {
1081 return true;
1082 }
1083 }
1084 return false;
1085#else
1086 return true;
1087#endif
1088}
1089
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001090void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
1091 // Though Post takes MessageData by raw pointer (last parameter), it still
1092 // takes it with ownership.
1093 Post(RTC_FROM_HERE, &queued_task_handler_,
1094 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1095}
1096
1097void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
1098 uint32_t milliseconds) {
Henrik Boströmcf9899c2022-01-20 09:46:16 +01001099 // This implementation does not support low precision yet.
1100 PostDelayedHighPrecisionTask(std::move(task), milliseconds);
1101}
1102
1103void Thread::PostDelayedHighPrecisionTask(
1104 std::unique_ptr<webrtc::QueuedTask> task,
1105 uint32_t milliseconds) {
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001106 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1107 // it still takes it with ownership.
Henrik Boströmcf9899c2022-01-20 09:46:16 +01001108 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_, /*id=*/0,
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001109 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1110}
1111
1112void Thread::Delete() {
1113 Stop();
1114 delete this;
1115}
1116
Niels Möller8909a632018-09-06 08:42:44 +02001117bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001118 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001119}
1120
Peter Boström0c4e06b2015-10-07 12:23:21 +02001121void Thread::Clear(MessageHandler* phandler,
1122 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001123 MessageList* removed) {
1124 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001125 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001126}
1127
1128bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001129 // Using ProcessMessages with a custom clock for testing and a time greater
1130 // than 0 doesn't work, since it's not guaranteed to advance the custom
1131 // clock's time, and may get stuck in an infinite loop.
1132 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1133 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001134 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001135 int cmsNext = cmsLoop;
1136
1137 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001138#if defined(WEBRTC_MAC)
1139 ScopedAutoReleasePool pool;
1140#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001141 Message msg;
1142 if (!Get(&msg, cmsNext))
1143 return !IsQuitting();
1144 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001145
kthelgasonde6adbe2017-02-22 00:42:11 -08001146 if (cmsLoop != kForever) {
1147 cmsNext = static_cast<int>(TimeUntil(msEnd));
1148 if (cmsNext < 0)
1149 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001150 }
1151 }
1152}
1153
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001154bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1155 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001156 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001157
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001158#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001159 if (need_synchronize_access) {
1160 // We explicitly ask for no rights other than synchronization.
1161 // This gives us the best chance of succeeding.
1162 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1163 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001164 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001165 return false;
1166 }
1167 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001168 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001169#elif defined(WEBRTC_POSIX)
1170 thread_ = pthread_self();
1171#endif
1172 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001173 thread_manager->SetCurrentThread(this);
1174 return true;
1175}
1176
Tommi51492422017-12-04 15:18:23 +01001177bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001178#if defined(WEBRTC_WIN)
1179 return thread_ != nullptr;
1180#elif defined(WEBRTC_POSIX)
1181 return thread_ != 0;
1182#endif
1183}
1184
Steve Antonbcc1a762019-12-11 11:21:53 -08001185// static
1186MessageHandler* Thread::GetPostTaskMessageHandler() {
1187 // Allocate at first call, never deallocate.
1188 static MessageHandler* handler = new MessageHandlerWithTask;
1189 return handler;
1190}
1191
Taylor Brandstetter08672602018-03-02 15:20:33 -08001192AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +01001193 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001194 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001195 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001196 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1197 // post a message to a queue that no running thread is serving.
1198 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001199 ThreadManager::Instance()->SetCurrentThread(this);
1200 }
1201}
1202
1203AutoThread::~AutoThread() {
1204 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001205 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001206 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001207 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001208 }
1209}
1210
nisse7eaa4ea2017-05-08 05:25:41 -07001211AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001212 : Thread(ss, /*do_init=*/false) {
1213 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001214 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001215 // Temporarily set the current thread to nullptr so that we can keep checks
1216 // around that catch unintentional pointer overwrites.
1217 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001218 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1219 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001220 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001221 }
1222}
1223
1224AutoSocketServerThread::~AutoSocketServerThread() {
1225 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
Steve Anton3b80aac2017-10-19 10:17:12 -07001226 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001227 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001228 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1229 // its contents rely on this thread still being set as the current thread.
1230 Stop();
1231 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001232 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001233 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1234 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001235 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001236 }
1237}
1238
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001239} // namespace rtc