blob: 4790a6f1d710c0235763dda62b9f38a25c6328e1 [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
Ali Tofigh7fa90572022-03-17 15:47:49 +010013#include "absl/strings/string_view.h"
Markus Handell82da9322022-12-16 15:50:24 +010014#include "api/task_queue/task_queue_base.h"
Markus Handell9a21c492022-08-25 11:40:13 +000015#include "api/units/time_delta.h"
16#include "rtc_base/socket_server.h"
Ali Tofigh7fa90572022-03-17 15:47:49 +010017
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000018#if defined(WEBRTC_WIN)
19#include <comdef.h>
20#elif defined(WEBRTC_POSIX)
21#include <time.h>
Tommi51492422017-12-04 15:18:23 +010022#else
23#error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024#endif
25
Artem Titov80d02ad2018-05-21 12:20:39 +020026#if defined(WEBRTC_WIN)
27// Disable warning that we don't care about:
28// warning C4722: destructor never returns, potential memory leak
29#pragma warning(disable : 4722)
30#endif
31
Yves Gerey988cc082018-10-23 12:03:01 +020032#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020033
Yves Gerey988cc082018-10-23 12:03:01 +020034#include <utility>
Yves Gerey2e00abc2018-10-05 15:39:24 +020035
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010036#include "absl/algorithm/container.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020037#include "absl/cleanup/cleanup.h"
Artem Titovd15a5752021-02-10 14:31:24 +010038#include "api/sequence_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/checks.h"
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +020040#include "rtc_base/event.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010041#include "rtc_base/internal/default_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080043#include "rtc_base/null_socket_server.h"
Danil Chapovalov3ab76d92022-09-23 12:39:21 +020044#include "rtc_base/synchronization/mutex.h"
Steve Anton10542f22019-01-11 09:11:00 -080045#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000047
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020048#if defined(WEBRTC_MAC)
49#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020050
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020051/*
52 * These are forward-declarations for methods that are part of the
53 * ObjC runtime. They are declared in the private header objc-internal.h.
54 * These calls are what clang inserts when using @autoreleasepool in ObjC,
55 * but here they are used directly in order to keep this file C++.
56 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
57 */
58extern "C" {
59void* objc_autoreleasePoolPush(void);
60void objc_autoreleasePoolPop(void* pool);
61}
62
63namespace {
64class ScopedAutoReleasePool {
65 public:
66 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
67 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
68
69 private:
70 void* const pool_;
71};
72} // namespace
73#endif
74
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000075namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080076
Danil Chapovalov3ab76d92022-09-23 12:39:21 +020077using ::webrtc::MutexLock;
Danil Chapovalov0bd16652022-08-24 18:35:45 +020078using ::webrtc::TimeDelta;
79
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +020081 static ThreadManager* const thread_manager = new ThreadManager();
82 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000083}
84
nisse7866cfe2017-04-26 01:45:31 -070085ThreadManager::~ThreadManager() {
86 // By above RTC_DEFINE_STATIC_LOCAL.
Artem Titovd3251962021-11-15 16:57:07 +010087 RTC_DCHECK_NOTREACHED() << "ThreadManager should never be destructed.";
nisse7866cfe2017-04-26 01:45:31 -070088}
89
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010091void ThreadManager::Add(Thread* message_queue) {
92 return Instance()->AddInternal(message_queue);
93}
94void ThreadManager::AddInternal(Thread* message_queue) {
Danil Chapovalovc3c89342023-01-02 09:21:29 +000095 MutexLock cs(&crit_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010096 message_queues_.push_back(message_queue);
97}
98
99// static
100void ThreadManager::Remove(Thread* message_queue) {
101 return Instance()->RemoveInternal(message_queue);
102}
103void ThreadManager::RemoveInternal(Thread* message_queue) {
104 {
Danil Chapovalovc3c89342023-01-02 09:21:29 +0000105 MutexLock cs(&crit_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100106 std::vector<Thread*>::iterator iter;
107 iter = absl::c_find(message_queues_, message_queue);
108 if (iter != message_queues_.end()) {
109 message_queues_.erase(iter);
110 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100111#if RTC_DCHECK_IS_ON
112 RemoveFromSendGraph(message_queue);
113#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100114 }
115}
116
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100117#if RTC_DCHECK_IS_ON
118void ThreadManager::RemoveFromSendGraph(Thread* thread) {
119 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
120 if (it->first == thread) {
121 it = send_graph_.erase(it);
122 } else {
123 it->second.erase(thread);
124 ++it;
125 }
126 }
127}
128
129void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
130 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200131 RTC_DCHECK(source);
132 RTC_DCHECK(target);
133
Danil Chapovalovc3c89342023-01-02 09:21:29 +0000134 MutexLock cs(&crit_);
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100135 std::deque<Thread*> all_targets({target});
136 // We check the pre-existing who-sends-to-who graph for any path from target
137 // to source. This loop is guaranteed to terminate because per the send graph
138 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800139 for (size_t i = 0; i < all_targets.size(); i++) {
140 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100141 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
142 }
143 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
144 << " send loop between " << source->name() << " and " << target->name();
145
146 // We may now insert source -> target without creating a cycle, since there
147 // was no path from target to source per the prior CHECK.
148 send_graph_[source].insert(target);
149}
150#endif
151
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100152// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100153void ThreadManager::ProcessAllMessageQueuesForTesting() {
154 return Instance()->ProcessAllMessageQueuesInternal();
155}
156
157void ThreadManager::ProcessAllMessageQueuesInternal() {
158 // This works by posting a delayed message at the current time and waiting
159 // for it to be dispatched on all queues, which will ensure that all messages
160 // that came before it were also dispatched.
Niels Möller7a669002022-06-27 09:47:02 +0200161 std::atomic<int> queues_not_done(0);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100162
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100163 {
Danil Chapovalovc3c89342023-01-02 09:21:29 +0000164 MutexLock cs(&crit_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100165 for (Thread* queue : message_queues_) {
166 if (!queue->IsProcessingMessagesForTesting()) {
167 // If the queue is not processing messages, it can
168 // be ignored. If we tried to post a message to it, it would be dropped
169 // or ignored.
170 continue;
171 }
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200172 queues_not_done.fetch_add(1);
173 // Whether the task is processed, or the thread is simply cleared,
174 // queues_not_done gets decremented.
175 absl::Cleanup sub = [&queues_not_done] { queues_not_done.fetch_sub(1); };
176 // Post delayed task instead of regular task to wait for all delayed tasks
177 // that are ready for processing.
178 queue->PostDelayedTask([sub = std::move(sub)] {}, TimeDelta::Zero());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100179 }
180 }
181
182 rtc::Thread* current = rtc::Thread::Current();
183 // Note: One of the message queues may have been on this thread, which is
184 // why we can't synchronously wait for queues_not_done to go to 0; we need
185 // to process messages as well.
Niels Möller7a669002022-06-27 09:47:02 +0200186 while (queues_not_done.load() > 0) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100187 if (current) {
188 current->ProcessMessages(0);
189 }
190 }
191}
192
193// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000194Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700195 ThreadManager* manager = ThreadManager::Instance();
196 Thread* thread = manager->CurrentThread();
197
nisse7866cfe2017-04-26 01:45:31 -0700198 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199}
200
201#if defined(WEBRTC_POSIX)
Niels Möller98d26df2022-02-07 10:35:29 +0100202ThreadManager::ThreadManager() {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200203#if defined(WEBRTC_MAC)
204 InitCocoaMultiThreading();
205#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800206 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000207}
208
Yves Gerey665174f2018-06-19 15:03:05 +0200209Thread* ThreadManager::CurrentThread() {
210 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000211}
212
Sebastian Jansson178a6852020-01-14 11:12:26 +0100213void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214 pthread_setspecific(key_, thread);
215}
216#endif
217
218#if defined(WEBRTC_WIN)
Niels Möller98d26df2022-02-07 10:35:29 +0100219ThreadManager::ThreadManager() : key_(TlsAlloc()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200220
221Thread* ThreadManager::CurrentThread() {
222 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223}
224
Sebastian Jansson178a6852020-01-14 11:12:26 +0100225void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226 TlsSetValue(key_, thread);
227}
228#endif
229
Sebastian Jansson178a6852020-01-14 11:12:26 +0100230void ThreadManager::SetCurrentThread(Thread* thread) {
231#if RTC_DLOG_IS_ON
232 if (CurrentThread() && thread) {
233 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
234 }
235#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200236
237 if (thread) {
238 thread->EnsureIsCurrentTaskQueue();
239 } else {
240 Thread* current = CurrentThread();
241 if (current) {
242 // The current thread is being cleared, e.g. as a result of
243 // UnwrapCurrent() being called or when a thread is being stopped
244 // (see PreRun()). This signals that the Thread instance is being detached
245 // from the thread, which also means that TaskQueue::Current() must not
246 // return a pointer to the Thread instance.
247 current->ClearCurrentTaskQueue();
248 }
249 }
250
Sebastian Jansson178a6852020-01-14 11:12:26 +0100251 SetCurrentThreadInternal(thread);
252}
253
254void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
255 SetCurrentThreadInternal(thread);
256}
257
Yves Gerey665174f2018-06-19 15:03:05 +0200258Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000259 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800260 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100261 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000262 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263 }
264 return result;
265}
266
267void ThreadManager::UnwrapCurrentThread() {
268 Thread* t = CurrentThread();
269 if (t && !(t->IsOwned())) {
270 t->UnwrapCurrent();
271 delete t;
272 }
273}
274
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000275Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200276 : thread_(Thread::Current()),
277 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000278
279Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800280 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000281 thread_->SetAllowBlockingCalls(previous_state_);
282}
283
Tommife041642021-04-07 10:08:28 +0200284#if RTC_DCHECK_IS_ON
285Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls(
286 std::function<void(uint32_t, uint32_t)> callback)
287 : thread_(Thread::Current()),
288 base_blocking_call_count_(thread_->GetBlockingCallCount()),
289 base_could_be_blocking_call_count_(
290 thread_->GetCouldBeBlockingCallCount()),
291 result_callback_(std::move(callback)) {}
292
293Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() {
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200294 if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) {
295 result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount());
296 }
Tommife041642021-04-07 10:08:28 +0200297}
298
299uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const {
300 return thread_->GetBlockingCallCount() - base_blocking_call_count_;
301}
302
303uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const {
304 return thread_->GetCouldBeBlockingCallCount() -
305 base_could_be_blocking_call_count_;
306}
307
308uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const {
309 return GetBlockingCallCount() + GetCouldBeBlockingCallCount();
310}
311#endif
312
Taylor Brandstetter08672602018-03-02 15:20:33 -0800313Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700314
315Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800316 : Thread(std::move(ss), /*do_init=*/true) {}
317
318Thread::Thread(SocketServer* ss, bool do_init)
Danil Chapovalov207f8532022-08-24 12:19:46 +0200319 : delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100320 fInitialized_(false),
321 fDestroyed_(false),
322 stop_(0),
323 ss_(ss) {
324 RTC_DCHECK(ss);
325 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800326 SetName("Thread", this); // default name
327 if (do_init) {
328 DoInit();
329 }
330}
331
332Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100333 : Thread(ss.get(), do_init) {
334 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335}
336
337Thread::~Thread() {
338 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800339 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000340}
341
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100342void Thread::DoInit() {
343 if (fInitialized_) {
344 return;
345 }
346
347 fInitialized_ = true;
348 ThreadManager::Add(this);
349}
350
351void Thread::DoDestroy() {
352 if (fDestroyed_) {
353 return;
354 }
355
356 fDestroyed_ = true;
357 // The signal is done from here to ensure
358 // that it always gets called when the queue
359 // is going away.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100360 if (ss_) {
361 ss_->SetMessageQueue(nullptr);
362 }
Niels Möller9bd24572021-04-19 12:18:27 +0200363 ThreadManager::Remove(this);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200364 // Clear.
Markus Handell82da9322022-12-16 15:50:24 +0100365 CurrentTaskQueueSetter set_current(this);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200366 messages_ = {};
367 delayed_messages_ = {};
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100368}
369
370SocketServer* Thread::socketserver() {
371 return ss_;
372}
373
374void Thread::WakeUpSocketServer() {
375 ss_->WakeUp();
376}
377
378void Thread::Quit() {
Niels Möller7a669002022-06-27 09:47:02 +0200379 stop_.store(1, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100380 WakeUpSocketServer();
381}
382
383bool Thread::IsQuitting() {
Niels Möller7a669002022-06-27 09:47:02 +0200384 return stop_.load(std::memory_order_acquire) != 0;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100385}
386
387void Thread::Restart() {
Niels Möller7a669002022-06-27 09:47:02 +0200388 stop_.store(0, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100389}
390
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200391absl::AnyInvocable<void() &&> Thread::Get(int cmsWait) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100392 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
393
394 int64_t cmsTotal = cmsWait;
395 int64_t cmsElapsed = 0;
396 int64_t msStart = TimeMillis();
397 int64_t msCurrent = msStart;
398 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100399 // Check for posted events
400 int64_t cmsDelayNext = kForever;
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200401 {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100402 // All queue operations need to be locked, but nothing else in this loop
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200403 // can happen while holding the `mutex_`.
404 MutexLock lock(&mutex_);
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200405 // Check for delayed messages that have been triggered and calculate the
406 // next trigger time.
407 while (!delayed_messages_.empty()) {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200408 if (msCurrent < delayed_messages_.top().run_time_ms) {
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200409 cmsDelayNext =
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200410 TimeDiff(delayed_messages_.top().run_time_ms, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100411 break;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100412 }
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200413 messages_.push(std::move(delayed_messages_.top().functor));
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200414 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100415 }
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200416 // Pull a message off the message queue, if available.
417 if (!messages_.empty()) {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200418 absl::AnyInvocable<void()&&> task = std::move(messages_.front());
419 messages_.pop();
420 return task;
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200421 }
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100422 }
423
424 if (IsQuitting())
425 break;
426
427 // Which is shorter, the delay wait or the asked wait?
428
429 int64_t cmsNext;
430 if (cmsWait == kForever) {
431 cmsNext = cmsDelayNext;
432 } else {
433 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
434 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
435 cmsNext = cmsDelayNext;
436 }
437
438 {
439 // Wait and multiplex in the meantime
Markus Handell9a21c492022-08-25 11:40:13 +0000440 if (!ss_->Wait(cmsNext == kForever ? SocketServer::kForever
441 : webrtc::TimeDelta::Millis(cmsNext),
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200442 /*process_io=*/true))
443 return nullptr;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100444 }
445
446 // If the specified timeout expired, return
447
448 msCurrent = TimeMillis();
449 cmsElapsed = TimeDiff(msCurrent, msStart);
450 if (cmsWait != kForever) {
451 if (cmsElapsed >= cmsWait)
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200452 return nullptr;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100453 }
454 }
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200455 return nullptr;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100456}
457
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200458void Thread::PostTask(absl::AnyInvocable<void() &&> task) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100459 if (IsQuitting()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100460 return;
461 }
462
463 // Keep thread safe
464 // Add the message to the end of the queue
465 // Signal for the multiplexer to return
466
467 {
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200468 MutexLock lock(&mutex_);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200469 messages_.push(std::move(task));
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100470 }
471 WakeUpSocketServer();
472}
473
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200474void Thread::PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
475 webrtc::TimeDelta delay) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100476 if (IsQuitting()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100477 return;
478 }
479
480 // Keep thread safe
481 // Add to the priority queue. Gets sorted soonest first.
482 // Signal for the multiplexer to return.
483
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200484 int64_t delay_ms = delay.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms<int>();
485 int64_t run_time_ms = TimeAfter(delay_ms);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100486 {
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200487 MutexLock lock(&mutex_);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200488 delayed_messages_.push({.delay_ms = delay_ms,
489 .run_time_ms = run_time_ms,
490 .message_number = delayed_next_num_,
491 .functor = std::move(task)});
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100492 // If this message queue processes 1 message every millisecond for 50 days,
493 // we will wrap this number. Even then, only messages with identical times
494 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100495 ++delayed_next_num_;
496 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100497 }
498 WakeUpSocketServer();
499}
500
501int Thread::GetDelay() {
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200502 MutexLock lock(&mutex_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100503
Sebastian Jansson61380c02020-01-17 14:46:08 +0100504 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100505 return 0;
506
Sebastian Jansson61380c02020-01-17 14:46:08 +0100507 if (!delayed_messages_.empty()) {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200508 int delay = TimeUntil(delayed_messages_.top().run_time_ms);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100509 if (delay < 0)
510 delay = 0;
511 return delay;
512 }
513
514 return kForever;
515}
516
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200517void Thread::Dispatch(absl::AnyInvocable<void() &&> task) {
518 TRACE_EVENT0("webrtc", "Thread::Dispatch");
Harald Alvestrandba694422021-01-27 21:52:14 +0000519 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100520 int64_t start_time = TimeMillis();
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200521 std::move(task)();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100522 int64_t end_time = TimeMillis();
523 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000524 if (diff >= dispatch_warning_ms_) {
525 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200526 << "ms to dispatch.";
Harald Alvestrandba694422021-01-27 21:52:14 +0000527 // To avoid log spew, move the warning limit to only give warning
528 // for delays that are larger than the one observed.
529 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100530 }
531}
532
nisse7866cfe2017-04-26 01:45:31 -0700533bool Thread::IsCurrent() const {
534 return ThreadManager::Instance()->CurrentThread() == this;
535}
536
danilchapbebf54c2016-04-28 01:32:48 -0700537std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100538 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700539}
540
541std::unique_ptr<Thread> Thread::Create() {
542 return std::unique_ptr<Thread>(
543 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
544}
545
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000546bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000547 AssertBlockingIsAllowedOnCurrentThread();
548
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549#if defined(WEBRTC_WIN)
550 ::Sleep(milliseconds);
551 return true;
552#else
553 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
554 // so we use nanosleep() even though it has greater precision than necessary.
555 struct timespec ts;
556 ts.tv_sec = milliseconds / 1000;
557 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800558 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000559 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100560 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000561 return false;
562 }
563 return true;
564#endif
565}
566
Ali Tofigh7fa90572022-03-17 15:47:49 +0100567bool Thread::SetName(absl::string_view name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100568 RTC_DCHECK(!IsRunning());
569
Ali Tofigh7fa90572022-03-17 15:47:49 +0100570 name_ = std::string(name);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000571 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200572 // The %p specifier typically produce at most 16 hex digits, possibly with a
573 // 0x prefix. But format is implementation defined, so add some margin.
574 char buf[30];
575 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000576 name_ += buf;
577 }
578 return true;
579}
580
Harald Alvestrandba694422021-01-27 21:52:14 +0000581void Thread::SetDispatchWarningMs(int deadline) {
582 if (!IsCurrent()) {
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200583 PostTask([this, deadline]() { SetDispatchWarningMs(deadline); });
Harald Alvestrandba694422021-01-27 21:52:14 +0000584 return;
585 }
586 RTC_DCHECK_RUN_ON(this);
587 dispatch_warning_ms_ = deadline;
588}
589
Niels Möllerd2e50132019-06-11 09:24:14 +0200590bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100591 RTC_DCHECK(!IsRunning());
592
593 if (IsRunning())
594 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000595
André Susano Pinto02a57972016-07-22 13:30:05 +0200596 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000597
598 // Make sure that ThreadManager is created on the main thread before
599 // we start a new thread.
600 ThreadManager::Instance();
601
Tommi51492422017-12-04 15:18:23 +0100602 owned_ = true;
603
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000604#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200605 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100606 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000607 return false;
608 }
609#elif defined(WEBRTC_POSIX)
610 pthread_attr_t attr;
611 pthread_attr_init(&attr);
612
Niels Möllerd2e50132019-06-11 09:24:14 +0200613 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000614 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100615 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100616 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000617 return false;
618 }
Tommi51492422017-12-04 15:18:23 +0100619 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000620#endif
621 return true;
622}
623
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000624bool Thread::WrapCurrent() {
625 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
626}
627
628void Thread::UnwrapCurrent() {
629 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800630 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000631#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800632 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000633 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100634 RTC_LOG_GLE(LS_ERROR)
635 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000636 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800637 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100638 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000639 }
Tommi51492422017-12-04 15:18:23 +0100640#elif defined(WEBRTC_POSIX)
641 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000642#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000643}
644
645void Thread::SafeWrapCurrent() {
646 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
647}
648
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000649void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100650 if (!IsRunning())
651 return;
652
653 RTC_DCHECK(!IsCurrent());
654 if (Current() && !Current()->blocking_calls_allowed_) {
655 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100656 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100657 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000658
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000659#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100660 RTC_DCHECK(thread_ != nullptr);
661 WaitForSingleObject(thread_, INFINITE);
662 CloseHandle(thread_);
663 thread_ = nullptr;
664 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000665#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100666 pthread_join(thread_, nullptr);
667 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000668#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000669}
670
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000671bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800672 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000673 bool previous = blocking_calls_allowed_;
674 blocking_calls_allowed_ = allow;
675 return previous;
676}
677
678// static
679void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700680#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000681 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800682 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000683#endif
684}
685
deadbeefdc20e262017-01-31 15:10:44 -0800686// static
687#if defined(WEBRTC_WIN)
688DWORD WINAPI Thread::PreRun(LPVOID pv) {
689#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000690void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800691#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200692 Thread* thread = static_cast<Thread*>(pv);
693 ThreadManager::Instance()->SetCurrentThread(thread);
694 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200695#if defined(WEBRTC_MAC)
696 ScopedAutoReleasePool pool;
697#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200698 thread->Run();
699
Tommi51492422017-12-04 15:18:23 +0100700 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800701#ifdef WEBRTC_WIN
702 return 0;
703#else
704 return nullptr;
705#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200706} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000707
708void Thread::Run() {
709 ProcessMessages(kForever);
710}
711
712bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100713 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000714 return owned_;
715}
716
717void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100718 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000719 Join();
720}
721
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200722void Thread::BlockingCall(rtc::FunctionView<void()> functor) {
723 TRACE_EVENT0("webrtc", "Thread::BlockingCall");
724
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100725 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200726 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000727 return;
728
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000729 if (IsCurrent()) {
Tommife041642021-04-07 10:08:28 +0200730#if RTC_DCHECK_IS_ON
Artem Titov15737162021-05-25 11:17:07 +0200731 RTC_DCHECK(this->IsInvokeToThreadAllowed(this));
Tommife041642021-04-07 10:08:28 +0200732 RTC_DCHECK_RUN_ON(this);
733 could_be_blocking_call_count_++;
734#endif
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200735 functor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000736 return;
737 }
738
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100739#if RTC_DCHECK_IS_ON
Danil Chapovalov2ded55e2023-01-27 15:06:37 +0000740 if (Thread* current_thread = Thread::Current()) {
Tommife041642021-04-07 10:08:28 +0200741 RTC_DCHECK_RUN_ON(current_thread);
Danil Chapovalov2ded55e2023-01-27 15:06:37 +0000742 RTC_DCHECK(current_thread->blocking_calls_allowed_);
Tommife041642021-04-07 10:08:28 +0200743 current_thread->blocking_call_count_++;
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200744 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
745 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
746 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000747 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200748#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000749
Danil Chapovalov2ded55e2023-01-27 15:06:37 +0000750 Event done;
751 absl::Cleanup cleanup = [&done] { done.Set(); };
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200752 PostTask([functor, cleanup = std::move(cleanup)] { functor(); });
Danil Chapovalov2ded55e2023-01-27 15:06:37 +0000753 done.Wait(Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000754}
755
Tommi6866dc72020-05-15 10:11:56 +0200756// Called by the ThreadManager when being set as the current thread.
757void Thread::EnsureIsCurrentTaskQueue() {
758 task_queue_registration_ =
759 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
760}
761
762// Called by the ThreadManager when being set as the current thread.
763void Thread::ClearCurrentTaskQueue() {
764 task_queue_registration_.reset();
765}
766
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200767void Thread::AllowInvokesToThread(Thread* thread) {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200768#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200769 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +0200770 PostTask([thread, this]() { AllowInvokesToThread(thread); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200771 return;
772 }
773 RTC_DCHECK_RUN_ON(this);
774 allowed_threads_.push_back(thread);
775 invoke_policy_enabled_ = true;
776#endif
777}
778
779void Thread::DisallowAllInvokes() {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200780#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200781 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +0200782 PostTask([this]() { DisallowAllInvokes(); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200783 return;
784 }
785 RTC_DCHECK_RUN_ON(this);
786 allowed_threads_.clear();
787 invoke_policy_enabled_ = true;
788#endif
789}
790
Tommife041642021-04-07 10:08:28 +0200791#if RTC_DCHECK_IS_ON
792uint32_t Thread::GetBlockingCallCount() const {
793 RTC_DCHECK_RUN_ON(this);
794 return blocking_call_count_;
795}
796uint32_t Thread::GetCouldBeBlockingCallCount() const {
797 RTC_DCHECK_RUN_ON(this);
798 return could_be_blocking_call_count_;
799}
800#endif
801
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200802// Returns true if no policies added or if there is at least one policy
Artem Titov96e3b992021-07-26 16:03:14 +0200803// that permits invocation to `target` thread.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200804bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200805#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200806 RTC_DCHECK_RUN_ON(this);
807 if (!invoke_policy_enabled_) {
808 return true;
809 }
810 for (const auto* thread : allowed_threads_) {
811 if (thread == target) {
812 return true;
813 }
814 }
815 return false;
816#else
817 return true;
818#endif
819}
820
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100821void Thread::Delete() {
822 Stop();
823 delete this;
824}
825
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200826void Thread::PostDelayedTask(absl::AnyInvocable<void() &&> task,
827 webrtc::TimeDelta delay) {
828 // This implementation does not support low precision yet.
829 PostDelayedHighPrecisionTask(std::move(task), delay);
830}
831
Niels Möller8909a632018-09-06 08:42:44 +0200832bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100833 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +0200834}
835
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000836bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700837 // Using ProcessMessages with a custom clock for testing and a time greater
838 // than 0 doesn't work, since it's not guaranteed to advance the custom
839 // clock's time, and may get stuck in an infinite loop.
840 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
841 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700842 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000843 int cmsNext = cmsLoop;
844
845 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200846#if defined(WEBRTC_MAC)
847 ScopedAutoReleasePool pool;
848#endif
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200849 absl::AnyInvocable<void()&&> task = Get(cmsNext);
850 if (!task)
kthelgasonde6adbe2017-02-22 00:42:11 -0800851 return !IsQuitting();
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200852 Dispatch(std::move(task));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000853
kthelgasonde6adbe2017-02-22 00:42:11 -0800854 if (cmsLoop != kForever) {
855 cmsNext = static_cast<int>(TimeUntil(msEnd));
856 if (cmsNext < 0)
857 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000858 }
859 }
860}
861
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000862bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
863 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100864 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000865
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000866#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000867 if (need_synchronize_access) {
868 // We explicitly ask for no rights other than synchronization.
869 // This gives us the best chance of succeeding.
870 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
871 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100872 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000873 return false;
874 }
875 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000876 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000877#elif defined(WEBRTC_POSIX)
878 thread_ = pthread_self();
879#endif
880 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000881 thread_manager->SetCurrentThread(this);
882 return true;
883}
884
Tommi51492422017-12-04 15:18:23 +0100885bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +0100886#if defined(WEBRTC_WIN)
887 return thread_ != nullptr;
888#elif defined(WEBRTC_POSIX)
889 return thread_ != 0;
890#endif
891}
892
Taylor Brandstetter08672602018-03-02 15:20:33 -0800893AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100894 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000895 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100896 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +0200897 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
898 // post a message to a queue that no running thread is serving.
899 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000900 ThreadManager::Instance()->SetCurrentThread(this);
901 }
902}
903
904AutoThread::~AutoThread() {
905 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700906 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000907 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800908 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000909 }
910}
911
nisse7eaa4ea2017-05-08 05:25:41 -0700912AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800913 : Thread(ss, /*do_init=*/false) {
914 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -0700915 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100916 // Temporarily set the current thread to nullptr so that we can keep checks
917 // around that catch unintentional pointer overwrites.
918 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700919 rtc::ThreadManager::Instance()->SetCurrentThread(this);
920 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100921 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -0700922 }
923}
924
925AutoSocketServerThread::~AutoSocketServerThread() {
926 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
Steve Anton3b80aac2017-10-19 10:17:12 -0700927 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100928 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -0700929 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
930 // its contents rely on this thread still being set as the current thread.
931 Stop();
932 DoDestroy();
Tommi51492422017-12-04 15:18:23 +0100933 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700934 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
935 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100936 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -0700937 }
938}
939
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000940} // namespace rtc