blob: fbf4105a8a442a4e41bb63253be0719ae58bd1da [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 Handell9a21c492022-08-25 11:40:13 +000014#include "api/units/time_delta.h"
15#include "rtc_base/socket_server.h"
Ali Tofigh7fa90572022-03-17 15:47:49 +010016
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017#if defined(WEBRTC_WIN)
18#include <comdef.h>
19#elif defined(WEBRTC_POSIX)
20#include <time.h>
Tommi51492422017-12-04 15:18:23 +010021#else
22#error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023#endif
24
Artem Titov80d02ad2018-05-21 12:20:39 +020025#if defined(WEBRTC_WIN)
26// Disable warning that we don't care about:
27// warning C4722: destructor never returns, potential memory leak
28#pragma warning(disable : 4722)
29#endif
30
Yves Gerey988cc082018-10-23 12:03:01 +020031#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020032
Yves Gerey988cc082018-10-23 12:03:01 +020033#include <utility>
Yves Gerey2e00abc2018-10-05 15:39:24 +020034
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010035#include "absl/algorithm/container.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020036#include "absl/cleanup/cleanup.h"
Artem Titovd15a5752021-02-10 14:31:24 +010037#include "api/sequence_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020039#include "rtc_base/deprecated/recursive_critical_section.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"
44#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000046
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020047#if defined(WEBRTC_MAC)
48#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020049
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020050/*
51 * These are forward-declarations for methods that are part of the
52 * ObjC runtime. They are declared in the private header objc-internal.h.
53 * These calls are what clang inserts when using @autoreleasepool in ObjC,
54 * but here they are used directly in order to keep this file C++.
55 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
56 */
57extern "C" {
58void* objc_autoreleasePoolPush(void);
59void objc_autoreleasePoolPop(void* pool);
60}
61
62namespace {
63class ScopedAutoReleasePool {
64 public:
65 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
66 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
67
68 private:
69 void* const pool_;
70};
71} // namespace
72#endif
73
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000074namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080075namespace {
76
Danil Chapovalov0bd16652022-08-24 18:35:45 +020077using ::webrtc::TimeDelta;
78
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010079class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
80 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020081 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
82 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010083 : cs_(cs), processing_(processing) {
84 cs_->Enter();
85 *processing_ += 1;
86 }
87
88 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
89 *processing_ -= 1;
90 cs_->Leave();
91 }
92
Byoungchan Lee14af7622022-01-12 05:24:58 +090093 MarkProcessingCritScope(const MarkProcessingCritScope&) = delete;
94 MarkProcessingCritScope& operator=(const MarkProcessingCritScope&) = delete;
95
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010096 private:
Markus Handell3cb525b2020-07-16 16:16:09 +020097 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010098 size_t* processing_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010099};
100
Steve Antonbcc1a762019-12-11 11:21:53 -0800101} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000102
103ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200104 static ThreadManager* const thread_manager = new ThreadManager();
105 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000106}
107
nisse7866cfe2017-04-26 01:45:31 -0700108ThreadManager::~ThreadManager() {
109 // By above RTC_DEFINE_STATIC_LOCAL.
Artem Titovd3251962021-11-15 16:57:07 +0100110 RTC_DCHECK_NOTREACHED() << "ThreadManager should never be destructed.";
nisse7866cfe2017-04-26 01:45:31 -0700111}
112
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000113// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100114void ThreadManager::Add(Thread* message_queue) {
115 return Instance()->AddInternal(message_queue);
116}
117void ThreadManager::AddInternal(Thread* message_queue) {
118 CritScope cs(&crit_);
119 // Prevent changes while the list of message queues is processed.
120 RTC_DCHECK_EQ(processing_, 0);
121 message_queues_.push_back(message_queue);
122}
123
124// static
125void ThreadManager::Remove(Thread* message_queue) {
126 return Instance()->RemoveInternal(message_queue);
127}
128void ThreadManager::RemoveInternal(Thread* message_queue) {
129 {
130 CritScope cs(&crit_);
131 // Prevent changes while the list of message queues is processed.
132 RTC_DCHECK_EQ(processing_, 0);
133 std::vector<Thread*>::iterator iter;
134 iter = absl::c_find(message_queues_, message_queue);
135 if (iter != message_queues_.end()) {
136 message_queues_.erase(iter);
137 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100138#if RTC_DCHECK_IS_ON
139 RemoveFromSendGraph(message_queue);
140#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100141 }
142}
143
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100144#if RTC_DCHECK_IS_ON
145void ThreadManager::RemoveFromSendGraph(Thread* thread) {
146 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
147 if (it->first == thread) {
148 it = send_graph_.erase(it);
149 } else {
150 it->second.erase(thread);
151 ++it;
152 }
153 }
154}
155
156void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
157 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200158 RTC_DCHECK(source);
159 RTC_DCHECK(target);
160
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100161 CritScope cs(&crit_);
162 std::deque<Thread*> all_targets({target});
163 // We check the pre-existing who-sends-to-who graph for any path from target
164 // to source. This loop is guaranteed to terminate because per the send graph
165 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800166 for (size_t i = 0; i < all_targets.size(); i++) {
167 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100168 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
169 }
170 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
171 << " send loop between " << source->name() << " and " << target->name();
172
173 // We may now insert source -> target without creating a cycle, since there
174 // was no path from target to source per the prior CHECK.
175 send_graph_[source].insert(target);
176}
177#endif
178
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100179// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100180void ThreadManager::ProcessAllMessageQueuesForTesting() {
181 return Instance()->ProcessAllMessageQueuesInternal();
182}
183
184void ThreadManager::ProcessAllMessageQueuesInternal() {
185 // This works by posting a delayed message at the current time and waiting
186 // for it to be dispatched on all queues, which will ensure that all messages
187 // that came before it were also dispatched.
Niels Möller7a669002022-06-27 09:47:02 +0200188 std::atomic<int> queues_not_done(0);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100189
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100190 {
191 MarkProcessingCritScope cs(&crit_, &processing_);
192 for (Thread* queue : message_queues_) {
193 if (!queue->IsProcessingMessagesForTesting()) {
194 // If the queue is not processing messages, it can
195 // be ignored. If we tried to post a message to it, it would be dropped
196 // or ignored.
197 continue;
198 }
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200199 queues_not_done.fetch_add(1);
200 // Whether the task is processed, or the thread is simply cleared,
201 // queues_not_done gets decremented.
202 absl::Cleanup sub = [&queues_not_done] { queues_not_done.fetch_sub(1); };
203 // Post delayed task instead of regular task to wait for all delayed tasks
204 // that are ready for processing.
205 queue->PostDelayedTask([sub = std::move(sub)] {}, TimeDelta::Zero());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100206 }
207 }
208
209 rtc::Thread* current = rtc::Thread::Current();
210 // Note: One of the message queues may have been on this thread, which is
211 // why we can't synchronously wait for queues_not_done to go to 0; we need
212 // to process messages as well.
Niels Möller7a669002022-06-27 09:47:02 +0200213 while (queues_not_done.load() > 0) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100214 if (current) {
215 current->ProcessMessages(0);
216 }
217 }
218}
219
220// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000221Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700222 ThreadManager* manager = ThreadManager::Instance();
223 Thread* thread = manager->CurrentThread();
224
nisse7866cfe2017-04-26 01:45:31 -0700225 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226}
227
228#if defined(WEBRTC_POSIX)
Niels Möller98d26df2022-02-07 10:35:29 +0100229ThreadManager::ThreadManager() {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200230#if defined(WEBRTC_MAC)
231 InitCocoaMultiThreading();
232#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800233 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234}
235
Yves Gerey665174f2018-06-19 15:03:05 +0200236Thread* ThreadManager::CurrentThread() {
237 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000238}
239
Sebastian Jansson178a6852020-01-14 11:12:26 +0100240void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000241 pthread_setspecific(key_, thread);
242}
243#endif
244
245#if defined(WEBRTC_WIN)
Niels Möller98d26df2022-02-07 10:35:29 +0100246ThreadManager::ThreadManager() : key_(TlsAlloc()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200247
248Thread* ThreadManager::CurrentThread() {
249 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250}
251
Sebastian Jansson178a6852020-01-14 11:12:26 +0100252void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000253 TlsSetValue(key_, thread);
254}
255#endif
256
Sebastian Jansson178a6852020-01-14 11:12:26 +0100257void ThreadManager::SetCurrentThread(Thread* thread) {
258#if RTC_DLOG_IS_ON
259 if (CurrentThread() && thread) {
260 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
261 }
262#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200263
264 if (thread) {
265 thread->EnsureIsCurrentTaskQueue();
266 } else {
267 Thread* current = CurrentThread();
268 if (current) {
269 // The current thread is being cleared, e.g. as a result of
270 // UnwrapCurrent() being called or when a thread is being stopped
271 // (see PreRun()). This signals that the Thread instance is being detached
272 // from the thread, which also means that TaskQueue::Current() must not
273 // return a pointer to the Thread instance.
274 current->ClearCurrentTaskQueue();
275 }
276 }
277
Sebastian Jansson178a6852020-01-14 11:12:26 +0100278 SetCurrentThreadInternal(thread);
279}
280
281void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
282 SetCurrentThreadInternal(thread);
283}
284
Yves Gerey665174f2018-06-19 15:03:05 +0200285Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800287 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100288 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000289 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290 }
291 return result;
292}
293
294void ThreadManager::UnwrapCurrentThread() {
295 Thread* t = CurrentThread();
296 if (t && !(t->IsOwned())) {
297 t->UnwrapCurrent();
298 delete t;
299 }
300}
301
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000302Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200303 : thread_(Thread::Current()),
304 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000305
306Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800307 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000308 thread_->SetAllowBlockingCalls(previous_state_);
309}
310
Tommife041642021-04-07 10:08:28 +0200311#if RTC_DCHECK_IS_ON
312Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls(
313 std::function<void(uint32_t, uint32_t)> callback)
314 : thread_(Thread::Current()),
315 base_blocking_call_count_(thread_->GetBlockingCallCount()),
316 base_could_be_blocking_call_count_(
317 thread_->GetCouldBeBlockingCallCount()),
318 result_callback_(std::move(callback)) {}
319
320Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() {
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200321 if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) {
322 result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount());
323 }
Tommife041642021-04-07 10:08:28 +0200324}
325
326uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const {
327 return thread_->GetBlockingCallCount() - base_blocking_call_count_;
328}
329
330uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const {
331 return thread_->GetCouldBeBlockingCallCount() -
332 base_could_be_blocking_call_count_;
333}
334
335uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const {
336 return GetBlockingCallCount() + GetCouldBeBlockingCallCount();
337}
338#endif
339
Taylor Brandstetter08672602018-03-02 15:20:33 -0800340Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700341
342Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800343 : Thread(std::move(ss), /*do_init=*/true) {}
344
345Thread::Thread(SocketServer* ss, bool do_init)
Danil Chapovalov207f8532022-08-24 12:19:46 +0200346 : delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100347 fInitialized_(false),
348 fDestroyed_(false),
349 stop_(0),
350 ss_(ss) {
351 RTC_DCHECK(ss);
352 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800353 SetName("Thread", this); // default name
354 if (do_init) {
355 DoInit();
356 }
357}
358
359Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100360 : Thread(ss.get(), do_init) {
361 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000362}
363
364Thread::~Thread() {
365 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800366 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000367}
368
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100369void Thread::DoInit() {
370 if (fInitialized_) {
371 return;
372 }
373
374 fInitialized_ = true;
375 ThreadManager::Add(this);
376}
377
378void Thread::DoDestroy() {
379 if (fDestroyed_) {
380 return;
381 }
382
383 fDestroyed_ = true;
384 // The signal is done from here to ensure
385 // that it always gets called when the queue
386 // is going away.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100387 if (ss_) {
388 ss_->SetMessageQueue(nullptr);
389 }
Niels Möller9bd24572021-04-19 12:18:27 +0200390 ThreadManager::Remove(this);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200391 // Clear.
392 messages_ = {};
393 delayed_messages_ = {};
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100394}
395
396SocketServer* Thread::socketserver() {
397 return ss_;
398}
399
400void Thread::WakeUpSocketServer() {
401 ss_->WakeUp();
402}
403
404void Thread::Quit() {
Niels Möller7a669002022-06-27 09:47:02 +0200405 stop_.store(1, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100406 WakeUpSocketServer();
407}
408
409bool Thread::IsQuitting() {
Niels Möller7a669002022-06-27 09:47:02 +0200410 return stop_.load(std::memory_order_acquire) != 0;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100411}
412
413void Thread::Restart() {
Niels Möller7a669002022-06-27 09:47:02 +0200414 stop_.store(0, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100415}
416
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200417absl::AnyInvocable<void() &&> Thread::Get(int cmsWait) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100418 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
419
420 int64_t cmsTotal = cmsWait;
421 int64_t cmsElapsed = 0;
422 int64_t msStart = TimeMillis();
423 int64_t msCurrent = msStart;
424 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100425 // Check for posted events
426 int64_t cmsDelayNext = kForever;
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200427 {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100428 // All queue operations need to be locked, but nothing else in this loop
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200429 // can happen inside the crit.
430 CritScope cs(&crit_);
431 // Check for delayed messages that have been triggered and calculate the
432 // next trigger time.
433 while (!delayed_messages_.empty()) {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200434 if (msCurrent < delayed_messages_.top().run_time_ms) {
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200435 cmsDelayNext =
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200436 TimeDiff(delayed_messages_.top().run_time_ms, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100437 break;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100438 }
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200439 messages_.push(std::move(delayed_messages_.top().functor));
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200440 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100441 }
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200442 // Pull a message off the message queue, if available.
443 if (!messages_.empty()) {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200444 absl::AnyInvocable<void()&&> task = std::move(messages_.front());
445 messages_.pop();
446 return task;
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200447 }
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100448 }
449
450 if (IsQuitting())
451 break;
452
453 // Which is shorter, the delay wait or the asked wait?
454
455 int64_t cmsNext;
456 if (cmsWait == kForever) {
457 cmsNext = cmsDelayNext;
458 } else {
459 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
460 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
461 cmsNext = cmsDelayNext;
462 }
463
464 {
465 // Wait and multiplex in the meantime
Markus Handell9a21c492022-08-25 11:40:13 +0000466 if (!ss_->Wait(cmsNext == kForever ? SocketServer::kForever
467 : webrtc::TimeDelta::Millis(cmsNext),
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200468 /*process_io=*/true))
469 return nullptr;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100470 }
471
472 // If the specified timeout expired, return
473
474 msCurrent = TimeMillis();
475 cmsElapsed = TimeDiff(msCurrent, msStart);
476 if (cmsWait != kForever) {
477 if (cmsElapsed >= cmsWait)
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200478 return nullptr;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100479 }
480 }
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200481 return nullptr;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100482}
483
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200484void Thread::PostTask(absl::AnyInvocable<void() &&> task) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100485 if (IsQuitting()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100486 return;
487 }
488
489 // Keep thread safe
490 // Add the message to the end of the queue
491 // Signal for the multiplexer to return
492
493 {
494 CritScope cs(&crit_);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200495 messages_.push(std::move(task));
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100496 }
497 WakeUpSocketServer();
498}
499
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200500void Thread::PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
501 webrtc::TimeDelta delay) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100502 if (IsQuitting()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100503 return;
504 }
505
506 // Keep thread safe
507 // Add to the priority queue. Gets sorted soonest first.
508 // Signal for the multiplexer to return.
509
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200510 int64_t delay_ms = delay.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms<int>();
511 int64_t run_time_ms = TimeAfter(delay_ms);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100512 {
513 CritScope cs(&crit_);
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200514 delayed_messages_.push({.delay_ms = delay_ms,
515 .run_time_ms = run_time_ms,
516 .message_number = delayed_next_num_,
517 .functor = std::move(task)});
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100518 // If this message queue processes 1 message every millisecond for 50 days,
519 // we will wrap this number. Even then, only messages with identical times
520 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100521 ++delayed_next_num_;
522 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100523 }
524 WakeUpSocketServer();
525}
526
527int Thread::GetDelay() {
528 CritScope cs(&crit_);
529
Sebastian Jansson61380c02020-01-17 14:46:08 +0100530 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100531 return 0;
532
Sebastian Jansson61380c02020-01-17 14:46:08 +0100533 if (!delayed_messages_.empty()) {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200534 int delay = TimeUntil(delayed_messages_.top().run_time_ms);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100535 if (delay < 0)
536 delay = 0;
537 return delay;
538 }
539
540 return kForever;
541}
542
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200543void Thread::Dispatch(absl::AnyInvocable<void() &&> task) {
544 TRACE_EVENT0("webrtc", "Thread::Dispatch");
Harald Alvestrandba694422021-01-27 21:52:14 +0000545 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100546 int64_t start_time = TimeMillis();
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200547 std::move(task)();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100548 int64_t end_time = TimeMillis();
549 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000550 if (diff >= dispatch_warning_ms_) {
551 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200552 << "ms to dispatch.";
Harald Alvestrandba694422021-01-27 21:52:14 +0000553 // To avoid log spew, move the warning limit to only give warning
554 // for delays that are larger than the one observed.
555 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100556 }
557}
558
nisse7866cfe2017-04-26 01:45:31 -0700559bool Thread::IsCurrent() const {
560 return ThreadManager::Instance()->CurrentThread() == this;
561}
562
danilchapbebf54c2016-04-28 01:32:48 -0700563std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100564 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700565}
566
567std::unique_ptr<Thread> Thread::Create() {
568 return std::unique_ptr<Thread>(
569 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
570}
571
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000572bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000573 AssertBlockingIsAllowedOnCurrentThread();
574
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000575#if defined(WEBRTC_WIN)
576 ::Sleep(milliseconds);
577 return true;
578#else
579 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
580 // so we use nanosleep() even though it has greater precision than necessary.
581 struct timespec ts;
582 ts.tv_sec = milliseconds / 1000;
583 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800584 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000585 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100586 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000587 return false;
588 }
589 return true;
590#endif
591}
592
Ali Tofigh7fa90572022-03-17 15:47:49 +0100593bool Thread::SetName(absl::string_view name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100594 RTC_DCHECK(!IsRunning());
595
Ali Tofigh7fa90572022-03-17 15:47:49 +0100596 name_ = std::string(name);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000597 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200598 // The %p specifier typically produce at most 16 hex digits, possibly with a
599 // 0x prefix. But format is implementation defined, so add some margin.
600 char buf[30];
601 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000602 name_ += buf;
603 }
604 return true;
605}
606
Harald Alvestrandba694422021-01-27 21:52:14 +0000607void Thread::SetDispatchWarningMs(int deadline) {
608 if (!IsCurrent()) {
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200609 PostTask([this, deadline]() { SetDispatchWarningMs(deadline); });
Harald Alvestrandba694422021-01-27 21:52:14 +0000610 return;
611 }
612 RTC_DCHECK_RUN_ON(this);
613 dispatch_warning_ms_ = deadline;
614}
615
Niels Möllerd2e50132019-06-11 09:24:14 +0200616bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100617 RTC_DCHECK(!IsRunning());
618
619 if (IsRunning())
620 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000621
André Susano Pinto02a57972016-07-22 13:30:05 +0200622 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000623
624 // Make sure that ThreadManager is created on the main thread before
625 // we start a new thread.
626 ThreadManager::Instance();
627
Tommi51492422017-12-04 15:18:23 +0100628 owned_ = true;
629
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000630#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200631 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100632 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000633 return false;
634 }
635#elif defined(WEBRTC_POSIX)
636 pthread_attr_t attr;
637 pthread_attr_init(&attr);
638
Niels Möllerd2e50132019-06-11 09:24:14 +0200639 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000640 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100641 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100642 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000643 return false;
644 }
Tommi51492422017-12-04 15:18:23 +0100645 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000646#endif
647 return true;
648}
649
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000650bool Thread::WrapCurrent() {
651 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
652}
653
654void Thread::UnwrapCurrent() {
655 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800656 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000657#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800658 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000659 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100660 RTC_LOG_GLE(LS_ERROR)
661 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000662 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800663 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100664 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000665 }
Tommi51492422017-12-04 15:18:23 +0100666#elif defined(WEBRTC_POSIX)
667 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000668#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000669}
670
671void Thread::SafeWrapCurrent() {
672 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
673}
674
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000675void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100676 if (!IsRunning())
677 return;
678
679 RTC_DCHECK(!IsCurrent());
680 if (Current() && !Current()->blocking_calls_allowed_) {
681 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100682 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100683 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000684
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000685#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100686 RTC_DCHECK(thread_ != nullptr);
687 WaitForSingleObject(thread_, INFINITE);
688 CloseHandle(thread_);
689 thread_ = nullptr;
690 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000691#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100692 pthread_join(thread_, nullptr);
693 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000694#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000695}
696
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000697bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800698 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000699 bool previous = blocking_calls_allowed_;
700 blocking_calls_allowed_ = allow;
701 return previous;
702}
703
704// static
705void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700706#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000707 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800708 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000709#endif
710}
711
deadbeefdc20e262017-01-31 15:10:44 -0800712// static
713#if defined(WEBRTC_WIN)
714DWORD WINAPI Thread::PreRun(LPVOID pv) {
715#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000716void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800717#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200718 Thread* thread = static_cast<Thread*>(pv);
719 ThreadManager::Instance()->SetCurrentThread(thread);
720 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200721#if defined(WEBRTC_MAC)
722 ScopedAutoReleasePool pool;
723#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200724 thread->Run();
725
Tommi51492422017-12-04 15:18:23 +0100726 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800727#ifdef WEBRTC_WIN
728 return 0;
729#else
730 return nullptr;
731#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200732} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000733
734void Thread::Run() {
735 ProcessMessages(kForever);
736}
737
738bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100739 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000740 return owned_;
741}
742
743void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100744 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000745 Join();
746}
747
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200748void Thread::BlockingCall(rtc::FunctionView<void()> functor) {
749 TRACE_EVENT0("webrtc", "Thread::BlockingCall");
750
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100751 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200752 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000753 return;
754
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000755 if (IsCurrent()) {
Tommife041642021-04-07 10:08:28 +0200756#if RTC_DCHECK_IS_ON
Artem Titov15737162021-05-25 11:17:07 +0200757 RTC_DCHECK(this->IsInvokeToThreadAllowed(this));
Tommife041642021-04-07 10:08:28 +0200758 RTC_DCHECK_RUN_ON(this);
759 could_be_blocking_call_count_++;
760#endif
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200761 functor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000762 return;
763 }
764
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000765 AssertBlockingIsAllowedOnCurrentThread();
766
Yves Gerey665174f2018-06-19 15:03:05 +0200767 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200768
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100769#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200770 if (current_thread) {
Tommife041642021-04-07 10:08:28 +0200771 RTC_DCHECK_RUN_ON(current_thread);
772 current_thread->blocking_call_count_++;
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200773 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
774 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
775 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000776 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200777#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000778
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200779 // Perhaps down the line we can get rid of this workaround and always require
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200780 // current_thread to be valid when BlockingCall() is called.
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200781 std::unique_ptr<rtc::Event> done_event;
782 if (!current_thread)
783 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000784
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200785 bool ready = false;
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200786 absl::Cleanup cleanup = [this, &ready, current_thread,
787 done = done_event.get()] {
788 if (current_thread) {
789 CritScope cs(&crit_);
790 ready = true;
791 current_thread->socketserver()->WakeUp();
792 } else {
793 done->Set();
794 }
795 };
Danil Chapovalovca1454a2022-09-13 13:12:25 +0200796 PostTask([functor, cleanup = std::move(cleanup)] { functor(); });
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200797 if (current_thread) {
798 bool waited = false;
799 crit_.Enter();
800 while (!ready) {
801 crit_.Leave();
Markus Handell9a21c492022-08-25 11:40:13 +0000802 current_thread->socketserver()->Wait(SocketServer::kForever, false);
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200803 waited = true;
804 crit_.Enter();
805 }
806 crit_.Leave();
807
808 // Our Wait loop above may have consumed some WakeUp events for this
809 // Thread, that weren't relevant to this Send. Losing these WakeUps can
810 // cause problems for some SocketServers.
811 //
812 // Concrete example:
813 // Win32SocketServer on thread A calls Send on thread B. While processing
814 // the message, thread B Posts a message to A. We consume the wakeup for
815 // that Post while waiting for the Send to complete, which means that when
816 // we exit this loop, we need to issue another WakeUp, or else the Posted
817 // message won't be processed in a timely manner.
818
819 if (waited) {
820 current_thread->socketserver()->WakeUp();
821 }
822 } else {
823 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000824 }
825}
826
Tommi6866dc72020-05-15 10:11:56 +0200827// Called by the ThreadManager when being set as the current thread.
828void Thread::EnsureIsCurrentTaskQueue() {
829 task_queue_registration_ =
830 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
831}
832
833// Called by the ThreadManager when being set as the current thread.
834void Thread::ClearCurrentTaskQueue() {
835 task_queue_registration_.reset();
836}
837
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200838void Thread::AllowInvokesToThread(Thread* thread) {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200839#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200840 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +0200841 PostTask([thread, this]() { AllowInvokesToThread(thread); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200842 return;
843 }
844 RTC_DCHECK_RUN_ON(this);
845 allowed_threads_.push_back(thread);
846 invoke_policy_enabled_ = true;
847#endif
848}
849
850void Thread::DisallowAllInvokes() {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200851#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200852 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +0200853 PostTask([this]() { DisallowAllInvokes(); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200854 return;
855 }
856 RTC_DCHECK_RUN_ON(this);
857 allowed_threads_.clear();
858 invoke_policy_enabled_ = true;
859#endif
860}
861
Tommife041642021-04-07 10:08:28 +0200862#if RTC_DCHECK_IS_ON
863uint32_t Thread::GetBlockingCallCount() const {
864 RTC_DCHECK_RUN_ON(this);
865 return blocking_call_count_;
866}
867uint32_t Thread::GetCouldBeBlockingCallCount() const {
868 RTC_DCHECK_RUN_ON(this);
869 return could_be_blocking_call_count_;
870}
871#endif
872
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200873// Returns true if no policies added or if there is at least one policy
Artem Titov96e3b992021-07-26 16:03:14 +0200874// that permits invocation to `target` thread.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200875bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200876#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200877 RTC_DCHECK_RUN_ON(this);
878 if (!invoke_policy_enabled_) {
879 return true;
880 }
881 for (const auto* thread : allowed_threads_) {
882 if (thread == target) {
883 return true;
884 }
885 }
886 return false;
887#else
888 return true;
889#endif
890}
891
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100892void Thread::Delete() {
893 Stop();
894 delete this;
895}
896
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200897void Thread::PostDelayedTask(absl::AnyInvocable<void() &&> task,
898 webrtc::TimeDelta delay) {
899 // This implementation does not support low precision yet.
900 PostDelayedHighPrecisionTask(std::move(task), delay);
901}
902
Niels Möller8909a632018-09-06 08:42:44 +0200903bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100904 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +0200905}
906
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000907bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700908 // Using ProcessMessages with a custom clock for testing and a time greater
909 // than 0 doesn't work, since it's not guaranteed to advance the custom
910 // clock's time, and may get stuck in an infinite loop.
911 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
912 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700913 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000914 int cmsNext = cmsLoop;
915
916 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200917#if defined(WEBRTC_MAC)
918 ScopedAutoReleasePool pool;
919#endif
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200920 absl::AnyInvocable<void()&&> task = Get(cmsNext);
921 if (!task)
kthelgasonde6adbe2017-02-22 00:42:11 -0800922 return !IsQuitting();
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200923 Dispatch(std::move(task));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000924
kthelgasonde6adbe2017-02-22 00:42:11 -0800925 if (cmsLoop != kForever) {
926 cmsNext = static_cast<int>(TimeUntil(msEnd));
927 if (cmsNext < 0)
928 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000929 }
930 }
931}
932
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000933bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
934 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100935 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000936
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000937#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000938 if (need_synchronize_access) {
939 // We explicitly ask for no rights other than synchronization.
940 // This gives us the best chance of succeeding.
941 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
942 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100943 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000944 return false;
945 }
946 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000947 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000948#elif defined(WEBRTC_POSIX)
949 thread_ = pthread_self();
950#endif
951 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000952 thread_manager->SetCurrentThread(this);
953 return true;
954}
955
Tommi51492422017-12-04 15:18:23 +0100956bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +0100957#if defined(WEBRTC_WIN)
958 return thread_ != nullptr;
959#elif defined(WEBRTC_POSIX)
960 return thread_ != 0;
961#endif
962}
963
Taylor Brandstetter08672602018-03-02 15:20:33 -0800964AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100965 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000966 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100967 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +0200968 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
969 // post a message to a queue that no running thread is serving.
970 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000971 ThreadManager::Instance()->SetCurrentThread(this);
972 }
973}
974
975AutoThread::~AutoThread() {
976 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700977 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000978 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800979 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000980 }
981}
982
nisse7eaa4ea2017-05-08 05:25:41 -0700983AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800984 : Thread(ss, /*do_init=*/false) {
985 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -0700986 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100987 // Temporarily set the current thread to nullptr so that we can keep checks
988 // around that catch unintentional pointer overwrites.
989 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700990 rtc::ThreadManager::Instance()->SetCurrentThread(this);
991 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100992 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -0700993 }
994}
995
996AutoSocketServerThread::~AutoSocketServerThread() {
997 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
Steve Anton3b80aac2017-10-19 10:17:12 -0700998 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100999 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001000 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1001 // its contents rely on this thread still being set as the current thread.
1002 Stop();
1003 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001004 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001005 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1006 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001007 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001008 }
1009}
1010
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001011} // namespace rtc