blob: 8c16949f5a1874c838cef7b6c25ae5820166fbd0 [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"
Markus Handell3cb525b2020-07-16 16:16:09 +020040#include "rtc_base/deprecated/recursive_critical_section.h"
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +020041#include "rtc_base/event.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010042#include "rtc_base/internal/default_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080044#include "rtc_base/null_socket_server.h"
Danil Chapovalov3ab76d92022-09-23 12:39:21 +020045#include "rtc_base/synchronization/mutex.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000048
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020049#if defined(WEBRTC_MAC)
50#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020051
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020052/*
53 * These are forward-declarations for methods that are part of the
54 * ObjC runtime. They are declared in the private header objc-internal.h.
55 * These calls are what clang inserts when using @autoreleasepool in ObjC,
56 * but here they are used directly in order to keep this file C++.
57 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
58 */
59extern "C" {
60void* objc_autoreleasePoolPush(void);
61void objc_autoreleasePoolPop(void* pool);
62}
63
64namespace {
65class ScopedAutoReleasePool {
66 public:
67 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
68 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
69
70 private:
71 void* const pool_;
72};
73} // namespace
74#endif
75
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000076namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080077namespace {
78
Danil Chapovalov3ab76d92022-09-23 12:39:21 +020079using ::webrtc::MutexLock;
Danil Chapovalov0bd16652022-08-24 18:35:45 +020080using ::webrtc::TimeDelta;
81
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010082class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
83 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020084 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
85 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010086 : cs_(cs), processing_(processing) {
87 cs_->Enter();
88 *processing_ += 1;
89 }
90
91 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
92 *processing_ -= 1;
93 cs_->Leave();
94 }
95
Byoungchan Lee14af7622022-01-12 05:24:58 +090096 MarkProcessingCritScope(const MarkProcessingCritScope&) = delete;
97 MarkProcessingCritScope& operator=(const MarkProcessingCritScope&) = delete;
98
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010099 private:
Markus Handell3cb525b2020-07-16 16:16:09 +0200100 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100101 size_t* processing_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100102};
103
Steve Antonbcc1a762019-12-11 11:21:53 -0800104} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000105
106ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200107 static ThreadManager* const thread_manager = new ThreadManager();
108 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000109}
110
nisse7866cfe2017-04-26 01:45:31 -0700111ThreadManager::~ThreadManager() {
112 // By above RTC_DEFINE_STATIC_LOCAL.
Artem Titovd3251962021-11-15 16:57:07 +0100113 RTC_DCHECK_NOTREACHED() << "ThreadManager should never be destructed.";
nisse7866cfe2017-04-26 01:45:31 -0700114}
115
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100117void ThreadManager::Add(Thread* message_queue) {
118 return Instance()->AddInternal(message_queue);
119}
120void ThreadManager::AddInternal(Thread* message_queue) {
121 CritScope cs(&crit_);
122 // Prevent changes while the list of message queues is processed.
123 RTC_DCHECK_EQ(processing_, 0);
124 message_queues_.push_back(message_queue);
125}
126
127// static
128void ThreadManager::Remove(Thread* message_queue) {
129 return Instance()->RemoveInternal(message_queue);
130}
131void ThreadManager::RemoveInternal(Thread* message_queue) {
132 {
133 CritScope cs(&crit_);
134 // Prevent changes while the list of message queues is processed.
135 RTC_DCHECK_EQ(processing_, 0);
136 std::vector<Thread*>::iterator iter;
137 iter = absl::c_find(message_queues_, message_queue);
138 if (iter != message_queues_.end()) {
139 message_queues_.erase(iter);
140 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100141#if RTC_DCHECK_IS_ON
142 RemoveFromSendGraph(message_queue);
143#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100144 }
145}
146
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100147#if RTC_DCHECK_IS_ON
148void ThreadManager::RemoveFromSendGraph(Thread* thread) {
149 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
150 if (it->first == thread) {
151 it = send_graph_.erase(it);
152 } else {
153 it->second.erase(thread);
154 ++it;
155 }
156 }
157}
158
159void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
160 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200161 RTC_DCHECK(source);
162 RTC_DCHECK(target);
163
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100164 CritScope cs(&crit_);
165 std::deque<Thread*> all_targets({target});
166 // We check the pre-existing who-sends-to-who graph for any path from target
167 // to source. This loop is guaranteed to terminate because per the send graph
168 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800169 for (size_t i = 0; i < all_targets.size(); i++) {
170 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100171 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
172 }
173 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
174 << " send loop between " << source->name() << " and " << target->name();
175
176 // We may now insert source -> target without creating a cycle, since there
177 // was no path from target to source per the prior CHECK.
178 send_graph_[source].insert(target);
179}
180#endif
181
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100182// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100183void ThreadManager::ProcessAllMessageQueuesForTesting() {
184 return Instance()->ProcessAllMessageQueuesInternal();
185}
186
187void ThreadManager::ProcessAllMessageQueuesInternal() {
188 // This works by posting a delayed message at the current time and waiting
189 // for it to be dispatched on all queues, which will ensure that all messages
190 // that came before it were also dispatched.
Niels Möller7a669002022-06-27 09:47:02 +0200191 std::atomic<int> queues_not_done(0);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100192
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100193 {
194 MarkProcessingCritScope cs(&crit_, &processing_);
195 for (Thread* queue : message_queues_) {
196 if (!queue->IsProcessingMessagesForTesting()) {
197 // If the queue is not processing messages, it can
198 // be ignored. If we tried to post a message to it, it would be dropped
199 // or ignored.
200 continue;
201 }
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200202 queues_not_done.fetch_add(1);
203 // Whether the task is processed, or the thread is simply cleared,
204 // queues_not_done gets decremented.
205 absl::Cleanup sub = [&queues_not_done] { queues_not_done.fetch_sub(1); };
206 // Post delayed task instead of regular task to wait for all delayed tasks
207 // that are ready for processing.
208 queue->PostDelayedTask([sub = std::move(sub)] {}, TimeDelta::Zero());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100209 }
210 }
211
212 rtc::Thread* current = rtc::Thread::Current();
213 // Note: One of the message queues may have been on this thread, which is
214 // why we can't synchronously wait for queues_not_done to go to 0; we need
215 // to process messages as well.
Niels Möller7a669002022-06-27 09:47:02 +0200216 while (queues_not_done.load() > 0) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100217 if (current) {
218 current->ProcessMessages(0);
219 }
220 }
221}
222
223// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000224Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700225 ThreadManager* manager = ThreadManager::Instance();
226 Thread* thread = manager->CurrentThread();
227
nisse7866cfe2017-04-26 01:45:31 -0700228 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229}
230
231#if defined(WEBRTC_POSIX)
Niels Möller98d26df2022-02-07 10:35:29 +0100232ThreadManager::ThreadManager() {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200233#if defined(WEBRTC_MAC)
234 InitCocoaMultiThreading();
235#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800236 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237}
238
Yves Gerey665174f2018-06-19 15:03:05 +0200239Thread* ThreadManager::CurrentThread() {
240 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000241}
242
Sebastian Jansson178a6852020-01-14 11:12:26 +0100243void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000244 pthread_setspecific(key_, thread);
245}
246#endif
247
248#if defined(WEBRTC_WIN)
Niels Möller98d26df2022-02-07 10:35:29 +0100249ThreadManager::ThreadManager() : key_(TlsAlloc()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200250
251Thread* ThreadManager::CurrentThread() {
252 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000253}
254
Sebastian Jansson178a6852020-01-14 11:12:26 +0100255void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256 TlsSetValue(key_, thread);
257}
258#endif
259
Sebastian Jansson178a6852020-01-14 11:12:26 +0100260void ThreadManager::SetCurrentThread(Thread* thread) {
261#if RTC_DLOG_IS_ON
262 if (CurrentThread() && thread) {
263 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
264 }
265#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200266
267 if (thread) {
268 thread->EnsureIsCurrentTaskQueue();
269 } else {
270 Thread* current = CurrentThread();
271 if (current) {
272 // The current thread is being cleared, e.g. as a result of
273 // UnwrapCurrent() being called or when a thread is being stopped
274 // (see PreRun()). This signals that the Thread instance is being detached
275 // from the thread, which also means that TaskQueue::Current() must not
276 // return a pointer to the Thread instance.
277 current->ClearCurrentTaskQueue();
278 }
279 }
280
Sebastian Jansson178a6852020-01-14 11:12:26 +0100281 SetCurrentThreadInternal(thread);
282}
283
284void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
285 SetCurrentThreadInternal(thread);
286}
287
Yves Gerey665174f2018-06-19 15:03:05 +0200288Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000289 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800290 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100291 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000292 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293 }
294 return result;
295}
296
297void ThreadManager::UnwrapCurrentThread() {
298 Thread* t = CurrentThread();
299 if (t && !(t->IsOwned())) {
300 t->UnwrapCurrent();
301 delete t;
302 }
303}
304
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000305Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200306 : thread_(Thread::Current()),
307 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000308
309Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800310 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000311 thread_->SetAllowBlockingCalls(previous_state_);
312}
313
Tommife041642021-04-07 10:08:28 +0200314#if RTC_DCHECK_IS_ON
315Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls(
316 std::function<void(uint32_t, uint32_t)> callback)
317 : thread_(Thread::Current()),
318 base_blocking_call_count_(thread_->GetBlockingCallCount()),
319 base_could_be_blocking_call_count_(
320 thread_->GetCouldBeBlockingCallCount()),
321 result_callback_(std::move(callback)) {}
322
323Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() {
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200324 if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) {
325 result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount());
326 }
Tommife041642021-04-07 10:08:28 +0200327}
328
329uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const {
330 return thread_->GetBlockingCallCount() - base_blocking_call_count_;
331}
332
333uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const {
334 return thread_->GetCouldBeBlockingCallCount() -
335 base_could_be_blocking_call_count_;
336}
337
338uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const {
339 return GetBlockingCallCount() + GetCouldBeBlockingCallCount();
340}
341#endif
342
Taylor Brandstetter08672602018-03-02 15:20:33 -0800343Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700344
345Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800346 : Thread(std::move(ss), /*do_init=*/true) {}
347
348Thread::Thread(SocketServer* ss, bool do_init)
Danil Chapovalov207f8532022-08-24 12:19:46 +0200349 : delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100350 fInitialized_(false),
351 fDestroyed_(false),
352 stop_(0),
353 ss_(ss) {
354 RTC_DCHECK(ss);
355 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800356 SetName("Thread", this); // default name
357 if (do_init) {
358 DoInit();
359 }
360}
361
362Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100363 : Thread(ss.get(), do_init) {
364 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000365}
366
367Thread::~Thread() {
368 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800369 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370}
371
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100372void Thread::DoInit() {
373 if (fInitialized_) {
374 return;
375 }
376
377 fInitialized_ = true;
378 ThreadManager::Add(this);
379}
380
381void Thread::DoDestroy() {
382 if (fDestroyed_) {
383 return;
384 }
385
386 fDestroyed_ = true;
387 // The signal is done from here to ensure
388 // that it always gets called when the queue
389 // is going away.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100390 if (ss_) {
391 ss_->SetMessageQueue(nullptr);
392 }
Niels Möller9bd24572021-04-19 12:18:27 +0200393 ThreadManager::Remove(this);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200394 // Clear.
Markus Handell82da9322022-12-16 15:50:24 +0100395 CurrentTaskQueueSetter set_current(this);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200396 messages_ = {};
397 delayed_messages_ = {};
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100398}
399
400SocketServer* Thread::socketserver() {
401 return ss_;
402}
403
404void Thread::WakeUpSocketServer() {
405 ss_->WakeUp();
406}
407
408void Thread::Quit() {
Niels Möller7a669002022-06-27 09:47:02 +0200409 stop_.store(1, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100410 WakeUpSocketServer();
411}
412
413bool Thread::IsQuitting() {
Niels Möller7a669002022-06-27 09:47:02 +0200414 return stop_.load(std::memory_order_acquire) != 0;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100415}
416
417void Thread::Restart() {
Niels Möller7a669002022-06-27 09:47:02 +0200418 stop_.store(0, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100419}
420
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200421absl::AnyInvocable<void() &&> Thread::Get(int cmsWait) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100422 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
423
424 int64_t cmsTotal = cmsWait;
425 int64_t cmsElapsed = 0;
426 int64_t msStart = TimeMillis();
427 int64_t msCurrent = msStart;
428 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100429 // Check for posted events
430 int64_t cmsDelayNext = kForever;
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200431 {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100432 // All queue operations need to be locked, but nothing else in this loop
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200433 // can happen while holding the `mutex_`.
434 MutexLock lock(&mutex_);
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200435 // Check for delayed messages that have been triggered and calculate the
436 // next trigger time.
437 while (!delayed_messages_.empty()) {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200438 if (msCurrent < delayed_messages_.top().run_time_ms) {
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200439 cmsDelayNext =
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200440 TimeDiff(delayed_messages_.top().run_time_ms, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100441 break;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100442 }
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200443 messages_.push(std::move(delayed_messages_.top().functor));
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200444 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100445 }
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200446 // Pull a message off the message queue, if available.
447 if (!messages_.empty()) {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200448 absl::AnyInvocable<void()&&> task = std::move(messages_.front());
449 messages_.pop();
450 return task;
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200451 }
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100452 }
453
454 if (IsQuitting())
455 break;
456
457 // Which is shorter, the delay wait or the asked wait?
458
459 int64_t cmsNext;
460 if (cmsWait == kForever) {
461 cmsNext = cmsDelayNext;
462 } else {
463 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
464 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
465 cmsNext = cmsDelayNext;
466 }
467
468 {
469 // Wait and multiplex in the meantime
Markus Handell9a21c492022-08-25 11:40:13 +0000470 if (!ss_->Wait(cmsNext == kForever ? SocketServer::kForever
471 : webrtc::TimeDelta::Millis(cmsNext),
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200472 /*process_io=*/true))
473 return nullptr;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100474 }
475
476 // If the specified timeout expired, return
477
478 msCurrent = TimeMillis();
479 cmsElapsed = TimeDiff(msCurrent, msStart);
480 if (cmsWait != kForever) {
481 if (cmsElapsed >= cmsWait)
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200482 return nullptr;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100483 }
484 }
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200485 return nullptr;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100486}
487
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200488void Thread::PostTask(absl::AnyInvocable<void() &&> task) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100489 if (IsQuitting()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100490 return;
491 }
492
493 // Keep thread safe
494 // Add the message to the end of the queue
495 // Signal for the multiplexer to return
496
497 {
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200498 MutexLock lock(&mutex_);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200499 messages_.push(std::move(task));
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100500 }
501 WakeUpSocketServer();
502}
503
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200504void Thread::PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
505 webrtc::TimeDelta delay) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100506 if (IsQuitting()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100507 return;
508 }
509
510 // Keep thread safe
511 // Add to the priority queue. Gets sorted soonest first.
512 // Signal for the multiplexer to return.
513
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200514 int64_t delay_ms = delay.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms<int>();
515 int64_t run_time_ms = TimeAfter(delay_ms);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100516 {
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200517 MutexLock lock(&mutex_);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200518 delayed_messages_.push({.delay_ms = delay_ms,
519 .run_time_ms = run_time_ms,
520 .message_number = delayed_next_num_,
521 .functor = std::move(task)});
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100522 // If this message queue processes 1 message every millisecond for 50 days,
523 // we will wrap this number. Even then, only messages with identical times
524 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100525 ++delayed_next_num_;
526 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100527 }
528 WakeUpSocketServer();
529}
530
531int Thread::GetDelay() {
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200532 MutexLock lock(&mutex_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100533
Sebastian Jansson61380c02020-01-17 14:46:08 +0100534 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100535 return 0;
536
Sebastian Jansson61380c02020-01-17 14:46:08 +0100537 if (!delayed_messages_.empty()) {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200538 int delay = TimeUntil(delayed_messages_.top().run_time_ms);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100539 if (delay < 0)
540 delay = 0;
541 return delay;
542 }
543
544 return kForever;
545}
546
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200547void Thread::Dispatch(absl::AnyInvocable<void() &&> task) {
548 TRACE_EVENT0("webrtc", "Thread::Dispatch");
Harald Alvestrandba694422021-01-27 21:52:14 +0000549 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100550 int64_t start_time = TimeMillis();
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200551 std::move(task)();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100552 int64_t end_time = TimeMillis();
553 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000554 if (diff >= dispatch_warning_ms_) {
555 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200556 << "ms to dispatch.";
Harald Alvestrandba694422021-01-27 21:52:14 +0000557 // To avoid log spew, move the warning limit to only give warning
558 // for delays that are larger than the one observed.
559 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100560 }
561}
562
nisse7866cfe2017-04-26 01:45:31 -0700563bool Thread::IsCurrent() const {
564 return ThreadManager::Instance()->CurrentThread() == this;
565}
566
danilchapbebf54c2016-04-28 01:32:48 -0700567std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100568 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700569}
570
571std::unique_ptr<Thread> Thread::Create() {
572 return std::unique_ptr<Thread>(
573 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
574}
575
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000576bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000577 AssertBlockingIsAllowedOnCurrentThread();
578
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000579#if defined(WEBRTC_WIN)
580 ::Sleep(milliseconds);
581 return true;
582#else
583 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
584 // so we use nanosleep() even though it has greater precision than necessary.
585 struct timespec ts;
586 ts.tv_sec = milliseconds / 1000;
587 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800588 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000589 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100590 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000591 return false;
592 }
593 return true;
594#endif
595}
596
Ali Tofigh7fa90572022-03-17 15:47:49 +0100597bool Thread::SetName(absl::string_view name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100598 RTC_DCHECK(!IsRunning());
599
Ali Tofigh7fa90572022-03-17 15:47:49 +0100600 name_ = std::string(name);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000601 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200602 // The %p specifier typically produce at most 16 hex digits, possibly with a
603 // 0x prefix. But format is implementation defined, so add some margin.
604 char buf[30];
605 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000606 name_ += buf;
607 }
608 return true;
609}
610
Harald Alvestrandba694422021-01-27 21:52:14 +0000611void Thread::SetDispatchWarningMs(int deadline) {
612 if (!IsCurrent()) {
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200613 PostTask([this, deadline]() { SetDispatchWarningMs(deadline); });
Harald Alvestrandba694422021-01-27 21:52:14 +0000614 return;
615 }
616 RTC_DCHECK_RUN_ON(this);
617 dispatch_warning_ms_ = deadline;
618}
619
Niels Möllerd2e50132019-06-11 09:24:14 +0200620bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100621 RTC_DCHECK(!IsRunning());
622
623 if (IsRunning())
624 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000625
André Susano Pinto02a57972016-07-22 13:30:05 +0200626 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000627
628 // Make sure that ThreadManager is created on the main thread before
629 // we start a new thread.
630 ThreadManager::Instance();
631
Tommi51492422017-12-04 15:18:23 +0100632 owned_ = true;
633
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000634#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200635 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100636 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000637 return false;
638 }
639#elif defined(WEBRTC_POSIX)
640 pthread_attr_t attr;
641 pthread_attr_init(&attr);
642
Niels Möllerd2e50132019-06-11 09:24:14 +0200643 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000644 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100645 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100646 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000647 return false;
648 }
Tommi51492422017-12-04 15:18:23 +0100649 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000650#endif
651 return true;
652}
653
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000654bool Thread::WrapCurrent() {
655 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
656}
657
658void Thread::UnwrapCurrent() {
659 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800660 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000661#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800662 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000663 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100664 RTC_LOG_GLE(LS_ERROR)
665 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000666 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800667 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100668 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000669 }
Tommi51492422017-12-04 15:18:23 +0100670#elif defined(WEBRTC_POSIX)
671 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000672#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000673}
674
675void Thread::SafeWrapCurrent() {
676 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
677}
678
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000679void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100680 if (!IsRunning())
681 return;
682
683 RTC_DCHECK(!IsCurrent());
684 if (Current() && !Current()->blocking_calls_allowed_) {
685 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100686 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100687 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000688
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000689#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100690 RTC_DCHECK(thread_ != nullptr);
691 WaitForSingleObject(thread_, INFINITE);
692 CloseHandle(thread_);
693 thread_ = nullptr;
694 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000695#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100696 pthread_join(thread_, nullptr);
697 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000698#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000699}
700
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000701bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800702 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000703 bool previous = blocking_calls_allowed_;
704 blocking_calls_allowed_ = allow;
705 return previous;
706}
707
708// static
709void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700710#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000711 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800712 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000713#endif
714}
715
deadbeefdc20e262017-01-31 15:10:44 -0800716// static
717#if defined(WEBRTC_WIN)
718DWORD WINAPI Thread::PreRun(LPVOID pv) {
719#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000720void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800721#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200722 Thread* thread = static_cast<Thread*>(pv);
723 ThreadManager::Instance()->SetCurrentThread(thread);
724 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200725#if defined(WEBRTC_MAC)
726 ScopedAutoReleasePool pool;
727#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200728 thread->Run();
729
Tommi51492422017-12-04 15:18:23 +0100730 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800731#ifdef WEBRTC_WIN
732 return 0;
733#else
734 return nullptr;
735#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200736} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000737
738void Thread::Run() {
739 ProcessMessages(kForever);
740}
741
742bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100743 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000744 return owned_;
745}
746
747void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100748 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000749 Join();
750}
751
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200752void Thread::BlockingCall(rtc::FunctionView<void()> functor) {
753 TRACE_EVENT0("webrtc", "Thread::BlockingCall");
754
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100755 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200756 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000757 return;
758
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000759 if (IsCurrent()) {
Tommife041642021-04-07 10:08:28 +0200760#if RTC_DCHECK_IS_ON
Artem Titov15737162021-05-25 11:17:07 +0200761 RTC_DCHECK(this->IsInvokeToThreadAllowed(this));
Tommife041642021-04-07 10:08:28 +0200762 RTC_DCHECK_RUN_ON(this);
763 could_be_blocking_call_count_++;
764#endif
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200765 functor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000766 return;
767 }
768
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000769 AssertBlockingIsAllowedOnCurrentThread();
770
Yves Gerey665174f2018-06-19 15:03:05 +0200771 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200772
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100773#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200774 if (current_thread) {
Tommife041642021-04-07 10:08:28 +0200775 RTC_DCHECK_RUN_ON(current_thread);
776 current_thread->blocking_call_count_++;
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200777 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
778 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
779 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000780 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200781#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000782
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200783 // Perhaps down the line we can get rid of this workaround and always require
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200784 // current_thread to be valid when BlockingCall() is called.
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200785 std::unique_ptr<rtc::Event> done_event;
786 if (!current_thread)
787 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000788
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200789 bool ready = false;
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200790 absl::Cleanup cleanup = [this, &ready, current_thread,
791 done = done_event.get()] {
792 if (current_thread) {
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200793 {
794 MutexLock lock(&mutex_);
795 ready = true;
796 }
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200797 current_thread->socketserver()->WakeUp();
798 } else {
799 done->Set();
800 }
801 };
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200802 PostTask([functor, cleanup = std::move(cleanup)] { functor(); });
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200803 if (current_thread) {
804 bool waited = false;
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200805 mutex_.Lock();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200806 while (!ready) {
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200807 mutex_.Unlock();
Markus Handell9a21c492022-08-25 11:40:13 +0000808 current_thread->socketserver()->Wait(SocketServer::kForever, false);
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200809 waited = true;
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200810 mutex_.Lock();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200811 }
Danil Chapovalov3ab76d92022-09-23 12:39:21 +0200812 mutex_.Unlock();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200813
814 // Our Wait loop above may have consumed some WakeUp events for this
815 // Thread, that weren't relevant to this Send. Losing these WakeUps can
816 // cause problems for some SocketServers.
817 //
818 // Concrete example:
819 // Win32SocketServer on thread A calls Send on thread B. While processing
820 // the message, thread B Posts a message to A. We consume the wakeup for
821 // that Post while waiting for the Send to complete, which means that when
822 // we exit this loop, we need to issue another WakeUp, or else the Posted
823 // message won't be processed in a timely manner.
824
825 if (waited) {
826 current_thread->socketserver()->WakeUp();
827 }
828 } else {
829 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000830 }
831}
832
Tommi6866dc72020-05-15 10:11:56 +0200833// Called by the ThreadManager when being set as the current thread.
834void Thread::EnsureIsCurrentTaskQueue() {
835 task_queue_registration_ =
836 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
837}
838
839// Called by the ThreadManager when being set as the current thread.
840void Thread::ClearCurrentTaskQueue() {
841 task_queue_registration_.reset();
842}
843
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200844void Thread::AllowInvokesToThread(Thread* thread) {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200845#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200846 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +0200847 PostTask([thread, this]() { AllowInvokesToThread(thread); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200848 return;
849 }
850 RTC_DCHECK_RUN_ON(this);
851 allowed_threads_.push_back(thread);
852 invoke_policy_enabled_ = true;
853#endif
854}
855
856void Thread::DisallowAllInvokes() {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200857#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200858 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +0200859 PostTask([this]() { DisallowAllInvokes(); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200860 return;
861 }
862 RTC_DCHECK_RUN_ON(this);
863 allowed_threads_.clear();
864 invoke_policy_enabled_ = true;
865#endif
866}
867
Tommife041642021-04-07 10:08:28 +0200868#if RTC_DCHECK_IS_ON
869uint32_t Thread::GetBlockingCallCount() const {
870 RTC_DCHECK_RUN_ON(this);
871 return blocking_call_count_;
872}
873uint32_t Thread::GetCouldBeBlockingCallCount() const {
874 RTC_DCHECK_RUN_ON(this);
875 return could_be_blocking_call_count_;
876}
877#endif
878
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200879// Returns true if no policies added or if there is at least one policy
Artem Titov96e3b992021-07-26 16:03:14 +0200880// that permits invocation to `target` thread.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200881bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200882#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200883 RTC_DCHECK_RUN_ON(this);
884 if (!invoke_policy_enabled_) {
885 return true;
886 }
887 for (const auto* thread : allowed_threads_) {
888 if (thread == target) {
889 return true;
890 }
891 }
892 return false;
893#else
894 return true;
895#endif
896}
897
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100898void Thread::Delete() {
899 Stop();
900 delete this;
901}
902
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200903void Thread::PostDelayedTask(absl::AnyInvocable<void() &&> task,
904 webrtc::TimeDelta delay) {
905 // This implementation does not support low precision yet.
906 PostDelayedHighPrecisionTask(std::move(task), delay);
907}
908
Niels Möller8909a632018-09-06 08:42:44 +0200909bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100910 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +0200911}
912
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000913bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700914 // Using ProcessMessages with a custom clock for testing and a time greater
915 // than 0 doesn't work, since it's not guaranteed to advance the custom
916 // clock's time, and may get stuck in an infinite loop.
917 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
918 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700919 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000920 int cmsNext = cmsLoop;
921
922 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200923#if defined(WEBRTC_MAC)
924 ScopedAutoReleasePool pool;
925#endif
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200926 absl::AnyInvocable<void()&&> task = Get(cmsNext);
927 if (!task)
kthelgasonde6adbe2017-02-22 00:42:11 -0800928 return !IsQuitting();
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200929 Dispatch(std::move(task));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000930
kthelgasonde6adbe2017-02-22 00:42:11 -0800931 if (cmsLoop != kForever) {
932 cmsNext = static_cast<int>(TimeUntil(msEnd));
933 if (cmsNext < 0)
934 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000935 }
936 }
937}
938
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000939bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
940 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100941 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000942
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000943#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000944 if (need_synchronize_access) {
945 // We explicitly ask for no rights other than synchronization.
946 // This gives us the best chance of succeeding.
947 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
948 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100949 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000950 return false;
951 }
952 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000953 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000954#elif defined(WEBRTC_POSIX)
955 thread_ = pthread_self();
956#endif
957 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000958 thread_manager->SetCurrentThread(this);
959 return true;
960}
961
Tommi51492422017-12-04 15:18:23 +0100962bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +0100963#if defined(WEBRTC_WIN)
964 return thread_ != nullptr;
965#elif defined(WEBRTC_POSIX)
966 return thread_ != 0;
967#endif
968}
969
Taylor Brandstetter08672602018-03-02 15:20:33 -0800970AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100971 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000972 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100973 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +0200974 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
975 // post a message to a queue that no running thread is serving.
976 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000977 ThreadManager::Instance()->SetCurrentThread(this);
978 }
979}
980
981AutoThread::~AutoThread() {
982 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700983 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000984 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800985 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000986 }
987}
988
nisse7eaa4ea2017-05-08 05:25:41 -0700989AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800990 : Thread(ss, /*do_init=*/false) {
991 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -0700992 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100993 // Temporarily set the current thread to nullptr so that we can keep checks
994 // around that catch unintentional pointer overwrites.
995 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700996 rtc::ThreadManager::Instance()->SetCurrentThread(this);
997 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100998 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -0700999 }
1000}
1001
1002AutoSocketServerThread::~AutoSocketServerThread() {
1003 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
Steve Anton3b80aac2017-10-19 10:17:12 -07001004 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001005 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001006 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1007 // its contents rely on this thread still being set as the current thread.
1008 Stop();
1009 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001010 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001011 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1012 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001013 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001014 }
1015}
1016
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001017} // namespace rtc