blob: 56b6b43ef31517d7b050454888a2cd63af163fb1 [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"
14
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015#if defined(WEBRTC_WIN)
16#include <comdef.h>
17#elif defined(WEBRTC_POSIX)
18#include <time.h>
Tommi51492422017-12-04 15:18:23 +010019#else
20#error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#endif
22
Artem Titov80d02ad2018-05-21 12:20:39 +020023#if defined(WEBRTC_WIN)
24// Disable warning that we don't care about:
25// warning C4722: destructor never returns, potential memory leak
26#pragma warning(disable : 4722)
27#endif
28
Yves Gerey988cc082018-10-23 12:03:01 +020029#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020030
Yves Gerey988cc082018-10-23 12:03:01 +020031#include <utility>
Yves Gerey2e00abc2018-10-05 15:39:24 +020032
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010033#include "absl/algorithm/container.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020034#include "absl/cleanup/cleanup.h"
Artem Titovd15a5752021-02-10 14:31:24 +010035#include "api/sequence_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020037#include "rtc_base/deprecated/recursive_critical_section.h"
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +020038#include "rtc_base/event.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010039#include "rtc_base/internal/default_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/null_socket_server.h"
42#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020045#if defined(WEBRTC_MAC)
46#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020047
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020048/*
49 * These are forward-declarations for methods that are part of the
50 * ObjC runtime. They are declared in the private header objc-internal.h.
51 * These calls are what clang inserts when using @autoreleasepool in ObjC,
52 * but here they are used directly in order to keep this file C++.
53 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
54 */
55extern "C" {
56void* objc_autoreleasePoolPush(void);
57void objc_autoreleasePoolPop(void* pool);
58}
59
60namespace {
61class ScopedAutoReleasePool {
62 public:
63 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
64 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
65
66 private:
67 void* const pool_;
68};
69} // namespace
70#endif
71
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080073namespace {
74
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020075struct AnyInvocableMessage final : public MessageData {
76 explicit AnyInvocableMessage(absl::AnyInvocable<void() &&> task)
77 : task(std::move(task)) {}
78 absl::AnyInvocable<void() &&> task;
79};
80
81class AnyInvocableMessageHandler final : public MessageHandler {
Steve Antonbcc1a762019-12-11 11:21:53 -080082 public:
Steve Antonbcc1a762019-12-11 11:21:53 -080083 void OnMessage(Message* msg) override {
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020084 std::move(static_cast<AnyInvocableMessage*>(msg->pdata)->task)();
Steve Antonbcc1a762019-12-11 11:21:53 -080085 delete msg->pdata;
86 }
Steve Antonbcc1a762019-12-11 11:21:53 -080087};
88
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020089MessageHandler* GetAnyInvocableMessageHandler() {
90 static MessageHandler* const handler = new AnyInvocableMessageHandler;
91 return handler;
92}
93
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010094class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
95 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020096 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
97 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010098 : cs_(cs), processing_(processing) {
99 cs_->Enter();
100 *processing_ += 1;
101 }
102
103 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
104 *processing_ -= 1;
105 cs_->Leave();
106 }
107
Byoungchan Lee14af7622022-01-12 05:24:58 +0900108 MarkProcessingCritScope(const MarkProcessingCritScope&) = delete;
109 MarkProcessingCritScope& operator=(const MarkProcessingCritScope&) = delete;
110
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100111 private:
Markus Handell3cb525b2020-07-16 16:16:09 +0200112 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100113 size_t* processing_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100114};
115
Steve Antonbcc1a762019-12-11 11:21:53 -0800116} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000117
118ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200119 static ThreadManager* const thread_manager = new ThreadManager();
120 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121}
122
nisse7866cfe2017-04-26 01:45:31 -0700123ThreadManager::~ThreadManager() {
124 // By above RTC_DEFINE_STATIC_LOCAL.
Artem Titovd3251962021-11-15 16:57:07 +0100125 RTC_DCHECK_NOTREACHED() << "ThreadManager should never be destructed.";
nisse7866cfe2017-04-26 01:45:31 -0700126}
127
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100129void ThreadManager::Add(Thread* message_queue) {
130 return Instance()->AddInternal(message_queue);
131}
132void ThreadManager::AddInternal(Thread* message_queue) {
133 CritScope cs(&crit_);
134 // Prevent changes while the list of message queues is processed.
135 RTC_DCHECK_EQ(processing_, 0);
136 message_queues_.push_back(message_queue);
137}
138
139// static
140void ThreadManager::Remove(Thread* message_queue) {
141 return Instance()->RemoveInternal(message_queue);
142}
143void ThreadManager::RemoveInternal(Thread* message_queue) {
144 {
145 CritScope cs(&crit_);
146 // Prevent changes while the list of message queues is processed.
147 RTC_DCHECK_EQ(processing_, 0);
148 std::vector<Thread*>::iterator iter;
149 iter = absl::c_find(message_queues_, message_queue);
150 if (iter != message_queues_.end()) {
151 message_queues_.erase(iter);
152 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100153#if RTC_DCHECK_IS_ON
154 RemoveFromSendGraph(message_queue);
155#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100156 }
157}
158
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100159#if RTC_DCHECK_IS_ON
160void ThreadManager::RemoveFromSendGraph(Thread* thread) {
161 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
162 if (it->first == thread) {
163 it = send_graph_.erase(it);
164 } else {
165 it->second.erase(thread);
166 ++it;
167 }
168 }
169}
170
171void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
172 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200173 RTC_DCHECK(source);
174 RTC_DCHECK(target);
175
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100176 CritScope cs(&crit_);
177 std::deque<Thread*> all_targets({target});
178 // We check the pre-existing who-sends-to-who graph for any path from target
179 // to source. This loop is guaranteed to terminate because per the send graph
180 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800181 for (size_t i = 0; i < all_targets.size(); i++) {
182 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100183 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
184 }
185 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
186 << " send loop between " << source->name() << " and " << target->name();
187
188 // We may now insert source -> target without creating a cycle, since there
189 // was no path from target to source per the prior CHECK.
190 send_graph_[source].insert(target);
191}
192#endif
193
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100194// static
195void ThreadManager::Clear(MessageHandler* handler) {
196 return Instance()->ClearInternal(handler);
197}
198void ThreadManager::ClearInternal(MessageHandler* handler) {
199 // Deleted objects may cause re-entrant calls to ClearInternal. This is
200 // allowed as the list of message queues does not change while queues are
201 // cleared.
202 MarkProcessingCritScope cs(&crit_, &processing_);
203 for (Thread* queue : message_queues_) {
204 queue->Clear(handler);
205 }
206}
207
208// static
209void ThreadManager::ProcessAllMessageQueuesForTesting() {
210 return Instance()->ProcessAllMessageQueuesInternal();
211}
212
213void ThreadManager::ProcessAllMessageQueuesInternal() {
214 // This works by posting a delayed message at the current time and waiting
215 // for it to be dispatched on all queues, which will ensure that all messages
216 // that came before it were also dispatched.
Niels Möller7a669002022-06-27 09:47:02 +0200217 std::atomic<int> queues_not_done(0);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100218
219 // This class is used so that whether the posted message is processed, or the
220 // message queue is simply cleared, queues_not_done gets decremented.
221 class ScopedIncrement : public MessageData {
222 public:
Niels Möller7a669002022-06-27 09:47:02 +0200223 ScopedIncrement(std::atomic<int>* value) : value_(value) {
224 value_->fetch_add(1);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100225 }
Niels Möller7a669002022-06-27 09:47:02 +0200226 ~ScopedIncrement() override { value_->fetch_sub(1); }
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100227
228 private:
Niels Möller7a669002022-06-27 09:47:02 +0200229 std::atomic<int>* value_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100230 };
231
232 {
233 MarkProcessingCritScope cs(&crit_, &processing_);
234 for (Thread* queue : message_queues_) {
235 if (!queue->IsProcessingMessagesForTesting()) {
236 // If the queue is not processing messages, it can
237 // be ignored. If we tried to post a message to it, it would be dropped
238 // or ignored.
239 continue;
240 }
241 queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
242 new ScopedIncrement(&queues_not_done));
243 }
244 }
245
246 rtc::Thread* current = rtc::Thread::Current();
247 // Note: One of the message queues may have been on this thread, which is
248 // why we can't synchronously wait for queues_not_done to go to 0; we need
249 // to process messages as well.
Niels Möller7a669002022-06-27 09:47:02 +0200250 while (queues_not_done.load() > 0) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100251 if (current) {
252 current->ProcessMessages(0);
253 }
254 }
255}
256
257// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700259 ThreadManager* manager = ThreadManager::Instance();
260 Thread* thread = manager->CurrentThread();
261
nisse7866cfe2017-04-26 01:45:31 -0700262 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263}
264
265#if defined(WEBRTC_POSIX)
Niels Möller98d26df2022-02-07 10:35:29 +0100266ThreadManager::ThreadManager() {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200267#if defined(WEBRTC_MAC)
268 InitCocoaMultiThreading();
269#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800270 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271}
272
Yves Gerey665174f2018-06-19 15:03:05 +0200273Thread* ThreadManager::CurrentThread() {
274 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275}
276
Sebastian Jansson178a6852020-01-14 11:12:26 +0100277void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278 pthread_setspecific(key_, thread);
279}
280#endif
281
282#if defined(WEBRTC_WIN)
Niels Möller98d26df2022-02-07 10:35:29 +0100283ThreadManager::ThreadManager() : key_(TlsAlloc()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200284
285Thread* ThreadManager::CurrentThread() {
286 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287}
288
Sebastian Jansson178a6852020-01-14 11:12:26 +0100289void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290 TlsSetValue(key_, thread);
291}
292#endif
293
Sebastian Jansson178a6852020-01-14 11:12:26 +0100294void ThreadManager::SetCurrentThread(Thread* thread) {
295#if RTC_DLOG_IS_ON
296 if (CurrentThread() && thread) {
297 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
298 }
299#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200300
301 if (thread) {
302 thread->EnsureIsCurrentTaskQueue();
303 } else {
304 Thread* current = CurrentThread();
305 if (current) {
306 // The current thread is being cleared, e.g. as a result of
307 // UnwrapCurrent() being called or when a thread is being stopped
308 // (see PreRun()). This signals that the Thread instance is being detached
309 // from the thread, which also means that TaskQueue::Current() must not
310 // return a pointer to the Thread instance.
311 current->ClearCurrentTaskQueue();
312 }
313 }
314
Sebastian Jansson178a6852020-01-14 11:12:26 +0100315 SetCurrentThreadInternal(thread);
316}
317
318void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
319 SetCurrentThreadInternal(thread);
320}
321
Yves Gerey665174f2018-06-19 15:03:05 +0200322Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800324 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100325 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000326 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000327 }
328 return result;
329}
330
331void ThreadManager::UnwrapCurrentThread() {
332 Thread* t = CurrentThread();
333 if (t && !(t->IsOwned())) {
334 t->UnwrapCurrent();
335 delete t;
336 }
337}
338
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000339Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200340 : thread_(Thread::Current()),
341 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000342
343Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800344 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000345 thread_->SetAllowBlockingCalls(previous_state_);
346}
347
Tommife041642021-04-07 10:08:28 +0200348#if RTC_DCHECK_IS_ON
349Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls(
350 std::function<void(uint32_t, uint32_t)> callback)
351 : thread_(Thread::Current()),
352 base_blocking_call_count_(thread_->GetBlockingCallCount()),
353 base_could_be_blocking_call_count_(
354 thread_->GetCouldBeBlockingCallCount()),
355 result_callback_(std::move(callback)) {}
356
357Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() {
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200358 if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) {
359 result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount());
360 }
Tommife041642021-04-07 10:08:28 +0200361}
362
363uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const {
364 return thread_->GetBlockingCallCount() - base_blocking_call_count_;
365}
366
367uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const {
368 return thread_->GetCouldBeBlockingCallCount() -
369 base_could_be_blocking_call_count_;
370}
371
372uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const {
373 return GetBlockingCallCount() + GetCouldBeBlockingCallCount();
374}
375#endif
376
Taylor Brandstetter08672602018-03-02 15:20:33 -0800377Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700378
379Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800380 : Thread(std::move(ss), /*do_init=*/true) {}
381
382Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100383 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100384 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100385 fInitialized_(false),
386 fDestroyed_(false),
387 stop_(0),
388 ss_(ss) {
389 RTC_DCHECK(ss);
390 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800391 SetName("Thread", this); // default name
392 if (do_init) {
393 DoInit();
394 }
395}
396
397Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100398 : Thread(ss.get(), do_init) {
399 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000400}
401
402Thread::~Thread() {
403 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800404 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000405}
406
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100407void Thread::DoInit() {
408 if (fInitialized_) {
409 return;
410 }
411
412 fInitialized_ = true;
413 ThreadManager::Add(this);
414}
415
416void Thread::DoDestroy() {
417 if (fDestroyed_) {
418 return;
419 }
420
421 fDestroyed_ = true;
422 // The signal is done from here to ensure
423 // that it always gets called when the queue
424 // is going away.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100425 if (ss_) {
426 ss_->SetMessageQueue(nullptr);
427 }
Niels Möller9bd24572021-04-19 12:18:27 +0200428 ThreadManager::Remove(this);
429 ClearInternal(nullptr, MQID_ANY, nullptr);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100430}
431
432SocketServer* Thread::socketserver() {
433 return ss_;
434}
435
436void Thread::WakeUpSocketServer() {
437 ss_->WakeUp();
438}
439
440void Thread::Quit() {
Niels Möller7a669002022-06-27 09:47:02 +0200441 stop_.store(1, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100442 WakeUpSocketServer();
443}
444
445bool Thread::IsQuitting() {
Niels Möller7a669002022-06-27 09:47:02 +0200446 return stop_.load(std::memory_order_acquire) != 0;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100447}
448
449void Thread::Restart() {
Niels Möller7a669002022-06-27 09:47:02 +0200450 stop_.store(0, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100451}
452
453bool Thread::Peek(Message* pmsg, int cmsWait) {
454 if (fPeekKeep_) {
455 *pmsg = msgPeek_;
456 return true;
457 }
458 if (!Get(pmsg, cmsWait))
459 return false;
460 msgPeek_ = *pmsg;
461 fPeekKeep_ = true;
462 return true;
463}
464
465bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
466 // Return and clear peek if present
467 // Always return the peek if it exists so there is Peek/Get symmetry
468
469 if (fPeekKeep_) {
470 *pmsg = msgPeek_;
471 fPeekKeep_ = false;
472 return true;
473 }
474
475 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
476
477 int64_t cmsTotal = cmsWait;
478 int64_t cmsElapsed = 0;
479 int64_t msStart = TimeMillis();
480 int64_t msCurrent = msStart;
481 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100482 // Check for posted events
483 int64_t cmsDelayNext = kForever;
484 bool first_pass = true;
485 while (true) {
486 // All queue operations need to be locked, but nothing else in this loop
487 // (specifically handling disposed message) can happen inside the crit.
488 // Otherwise, disposed MessageHandlers will cause deadlocks.
489 {
490 CritScope cs(&crit_);
491 // On the first pass, check for delayed messages that have been
492 // triggered and calculate the next trigger time.
493 if (first_pass) {
494 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100495 while (!delayed_messages_.empty()) {
496 if (msCurrent < delayed_messages_.top().run_time_ms_) {
497 cmsDelayNext =
498 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100499 break;
500 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100501 messages_.push_back(delayed_messages_.top().msg_);
502 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100503 }
504 }
505 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100506 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100507 break;
508 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100509 *pmsg = messages_.front();
510 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100511 }
512 } // crit_ is released here.
513
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100514 // If this was a dispose message, delete it and skip it.
515 if (MQID_DISPOSE == pmsg->message_id) {
516 RTC_DCHECK(nullptr == pmsg->phandler);
517 delete pmsg->pdata;
518 *pmsg = Message();
519 continue;
520 }
521 return true;
522 }
523
524 if (IsQuitting())
525 break;
526
527 // Which is shorter, the delay wait or the asked wait?
528
529 int64_t cmsNext;
530 if (cmsWait == kForever) {
531 cmsNext = cmsDelayNext;
532 } else {
533 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
534 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
535 cmsNext = cmsDelayNext;
536 }
537
538 {
539 // Wait and multiplex in the meantime
540 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
541 return false;
542 }
543
544 // If the specified timeout expired, return
545
546 msCurrent = TimeMillis();
547 cmsElapsed = TimeDiff(msCurrent, msStart);
548 if (cmsWait != kForever) {
549 if (cmsElapsed >= cmsWait)
550 return false;
551 }
552 }
553 return false;
554}
555
556void Thread::Post(const Location& posted_from,
557 MessageHandler* phandler,
558 uint32_t id,
559 MessageData* pdata,
560 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100561 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100562 if (IsQuitting()) {
563 delete pdata;
564 return;
565 }
566
567 // Keep thread safe
568 // Add the message to the end of the queue
569 // Signal for the multiplexer to return
570
571 {
572 CritScope cs(&crit_);
573 Message msg;
574 msg.posted_from = posted_from;
575 msg.phandler = phandler;
576 msg.message_id = id;
577 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100578 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100579 }
580 WakeUpSocketServer();
581}
582
583void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100584 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100585 MessageHandler* phandler,
586 uint32_t id,
587 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100588 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100589 pdata);
590}
591
592void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100593 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100594 MessageHandler* phandler,
595 uint32_t id,
596 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100597 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100598 pdata);
599}
600
601void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100602 int64_t delay_ms,
603 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100604 MessageHandler* phandler,
605 uint32_t id,
606 MessageData* pdata) {
607 if (IsQuitting()) {
608 delete pdata;
609 return;
610 }
611
612 // Keep thread safe
613 // Add to the priority queue. Gets sorted soonest first.
614 // Signal for the multiplexer to return.
615
616 {
617 CritScope cs(&crit_);
618 Message msg;
619 msg.posted_from = posted_from;
620 msg.phandler = phandler;
621 msg.message_id = id;
622 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100623 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
624 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100625 // If this message queue processes 1 message every millisecond for 50 days,
626 // we will wrap this number. Even then, only messages with identical times
627 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100628 ++delayed_next_num_;
629 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100630 }
631 WakeUpSocketServer();
632}
633
634int Thread::GetDelay() {
635 CritScope cs(&crit_);
636
Sebastian Jansson61380c02020-01-17 14:46:08 +0100637 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100638 return 0;
639
Sebastian Jansson61380c02020-01-17 14:46:08 +0100640 if (!delayed_messages_.empty()) {
641 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100642 if (delay < 0)
643 delay = 0;
644 return delay;
645 }
646
647 return kForever;
648}
649
650void Thread::ClearInternal(MessageHandler* phandler,
651 uint32_t id,
652 MessageList* removed) {
653 // Remove messages with phandler
654
655 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
656 if (removed) {
657 removed->push_back(msgPeek_);
658 } else {
659 delete msgPeek_.pdata;
660 }
661 fPeekKeep_ = false;
662 }
663
664 // Remove from ordered message queue
665
Sebastian Jansson61380c02020-01-17 14:46:08 +0100666 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100667 if (it->Match(phandler, id)) {
668 if (removed) {
669 removed->push_back(*it);
670 } else {
671 delete it->pdata;
672 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100673 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100674 } else {
675 ++it;
676 }
677 }
678
679 // Remove from priority queue. Not directly iterable, so use this approach
680
Sebastian Jansson61380c02020-01-17 14:46:08 +0100681 auto new_end = delayed_messages_.container().begin();
682 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100683 if (it->msg_.Match(phandler, id)) {
684 if (removed) {
685 removed->push_back(it->msg_);
686 } else {
687 delete it->msg_.pdata;
688 }
689 } else {
690 *new_end++ = *it;
691 }
692 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100693 delayed_messages_.container().erase(new_end,
694 delayed_messages_.container().end());
695 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100696}
697
698void Thread::Dispatch(Message* pmsg) {
699 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
700 pmsg->posted_from.file_name(), "src_func",
701 pmsg->posted_from.function_name());
Harald Alvestrandba694422021-01-27 21:52:14 +0000702 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100703 int64_t start_time = TimeMillis();
704 pmsg->phandler->OnMessage(pmsg);
705 int64_t end_time = TimeMillis();
706 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000707 if (diff >= dispatch_warning_ms_) {
708 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100709 << "ms to dispatch. Posted from: "
710 << pmsg->posted_from.ToString();
Harald Alvestrandba694422021-01-27 21:52:14 +0000711 // To avoid log spew, move the warning limit to only give warning
712 // for delays that are larger than the one observed.
713 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100714 }
715}
716
nisse7866cfe2017-04-26 01:45:31 -0700717bool Thread::IsCurrent() const {
718 return ThreadManager::Instance()->CurrentThread() == this;
719}
720
danilchapbebf54c2016-04-28 01:32:48 -0700721std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100722 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700723}
724
725std::unique_ptr<Thread> Thread::Create() {
726 return std::unique_ptr<Thread>(
727 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
728}
729
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000730bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000731 AssertBlockingIsAllowedOnCurrentThread();
732
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000733#if defined(WEBRTC_WIN)
734 ::Sleep(milliseconds);
735 return true;
736#else
737 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
738 // so we use nanosleep() even though it has greater precision than necessary.
739 struct timespec ts;
740 ts.tv_sec = milliseconds / 1000;
741 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800742 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000743 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100744 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000745 return false;
746 }
747 return true;
748#endif
749}
750
Ali Tofigh7fa90572022-03-17 15:47:49 +0100751bool Thread::SetName(absl::string_view name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100752 RTC_DCHECK(!IsRunning());
753
Ali Tofigh7fa90572022-03-17 15:47:49 +0100754 name_ = std::string(name);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000755 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200756 // The %p specifier typically produce at most 16 hex digits, possibly with a
757 // 0x prefix. But format is implementation defined, so add some margin.
758 char buf[30];
759 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000760 name_ += buf;
761 }
762 return true;
763}
764
Harald Alvestrandba694422021-01-27 21:52:14 +0000765void Thread::SetDispatchWarningMs(int deadline) {
766 if (!IsCurrent()) {
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200767 PostTask([this, deadline]() { SetDispatchWarningMs(deadline); });
Harald Alvestrandba694422021-01-27 21:52:14 +0000768 return;
769 }
770 RTC_DCHECK_RUN_ON(this);
771 dispatch_warning_ms_ = deadline;
772}
773
Niels Möllerd2e50132019-06-11 09:24:14 +0200774bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100775 RTC_DCHECK(!IsRunning());
776
777 if (IsRunning())
778 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000779
André Susano Pinto02a57972016-07-22 13:30:05 +0200780 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000781
782 // Make sure that ThreadManager is created on the main thread before
783 // we start a new thread.
784 ThreadManager::Instance();
785
Tommi51492422017-12-04 15:18:23 +0100786 owned_ = true;
787
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000788#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200789 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100790 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000791 return false;
792 }
793#elif defined(WEBRTC_POSIX)
794 pthread_attr_t attr;
795 pthread_attr_init(&attr);
796
Niels Möllerd2e50132019-06-11 09:24:14 +0200797 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000798 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100799 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100800 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000801 return false;
802 }
Tommi51492422017-12-04 15:18:23 +0100803 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000804#endif
805 return true;
806}
807
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000808bool Thread::WrapCurrent() {
809 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
810}
811
812void Thread::UnwrapCurrent() {
813 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800814 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000815#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800816 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000817 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100818 RTC_LOG_GLE(LS_ERROR)
819 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000820 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800821 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100822 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000823 }
Tommi51492422017-12-04 15:18:23 +0100824#elif defined(WEBRTC_POSIX)
825 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000826#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000827}
828
829void Thread::SafeWrapCurrent() {
830 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
831}
832
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000833void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100834 if (!IsRunning())
835 return;
836
837 RTC_DCHECK(!IsCurrent());
838 if (Current() && !Current()->blocking_calls_allowed_) {
839 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100840 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100841 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000842
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000843#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100844 RTC_DCHECK(thread_ != nullptr);
845 WaitForSingleObject(thread_, INFINITE);
846 CloseHandle(thread_);
847 thread_ = nullptr;
848 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000849#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100850 pthread_join(thread_, nullptr);
851 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000852#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000853}
854
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000855bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800856 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000857 bool previous = blocking_calls_allowed_;
858 blocking_calls_allowed_ = allow;
859 return previous;
860}
861
862// static
863void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700864#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000865 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800866 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000867#endif
868}
869
deadbeefdc20e262017-01-31 15:10:44 -0800870// static
871#if defined(WEBRTC_WIN)
872DWORD WINAPI Thread::PreRun(LPVOID pv) {
873#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000874void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800875#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200876 Thread* thread = static_cast<Thread*>(pv);
877 ThreadManager::Instance()->SetCurrentThread(thread);
878 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200879#if defined(WEBRTC_MAC)
880 ScopedAutoReleasePool pool;
881#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200882 thread->Run();
883
Tommi51492422017-12-04 15:18:23 +0100884 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800885#ifdef WEBRTC_WIN
886 return 0;
887#else
888 return nullptr;
889#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200890} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000891
892void Thread::Run() {
893 ProcessMessages(kForever);
894}
895
896bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100897 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000898 return owned_;
899}
900
901void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100902 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000903 Join();
904}
905
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700906void Thread::Send(const Location& posted_from,
907 MessageHandler* phandler,
908 uint32_t id,
909 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100910 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200911 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000912 return;
913
914 // Sent messages are sent to the MessageHandler directly, in the context
915 // of "thread", like Win32 SendMessage. If in the right context,
916 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000917 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700918 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000919 msg.phandler = phandler;
920 msg.message_id = id;
921 msg.pdata = pdata;
922 if (IsCurrent()) {
Tommife041642021-04-07 10:08:28 +0200923#if RTC_DCHECK_IS_ON
Artem Titov15737162021-05-25 11:17:07 +0200924 RTC_DCHECK(this->IsInvokeToThreadAllowed(this));
Tommife041642021-04-07 10:08:28 +0200925 RTC_DCHECK_RUN_ON(this);
926 could_be_blocking_call_count_++;
927#endif
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100928 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000929 return;
930 }
931
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000932 AssertBlockingIsAllowedOnCurrentThread();
933
Yves Gerey665174f2018-06-19 15:03:05 +0200934 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200935
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100936#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200937 if (current_thread) {
Tommife041642021-04-07 10:08:28 +0200938 RTC_DCHECK_RUN_ON(current_thread);
939 current_thread->blocking_call_count_++;
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200940 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
941 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
942 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000943 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200944#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000945
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200946 // Perhaps down the line we can get rid of this workaround and always require
947 // current_thread to be valid when Send() is called.
948 std::unique_ptr<rtc::Event> done_event;
949 if (!current_thread)
950 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000951
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200952 bool ready = false;
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200953 absl::Cleanup cleanup = [this, &ready, current_thread,
954 done = done_event.get()] {
955 if (current_thread) {
956 CritScope cs(&crit_);
957 ready = true;
958 current_thread->socketserver()->WakeUp();
959 } else {
960 done->Set();
961 }
962 };
963 PostTask([&msg, cleanup = std::move(cleanup)]() mutable {
964 msg.phandler->OnMessage(&msg);
965 });
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200966 if (current_thread) {
967 bool waited = false;
968 crit_.Enter();
969 while (!ready) {
970 crit_.Leave();
971 current_thread->socketserver()->Wait(kForever, false);
972 waited = true;
973 crit_.Enter();
974 }
975 crit_.Leave();
976
977 // Our Wait loop above may have consumed some WakeUp events for this
978 // Thread, that weren't relevant to this Send. Losing these WakeUps can
979 // cause problems for some SocketServers.
980 //
981 // Concrete example:
982 // Win32SocketServer on thread A calls Send on thread B. While processing
983 // the message, thread B Posts a message to A. We consume the wakeup for
984 // that Post while waiting for the Send to complete, which means that when
985 // we exit this loop, we need to issue another WakeUp, or else the Posted
986 // message won't be processed in a timely manner.
987
988 if (waited) {
989 current_thread->socketserver()->WakeUp();
990 }
991 } else {
992 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000993 }
994}
995
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700996void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100997 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800998 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
999 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +01001000
1001 class FunctorMessageHandler : public MessageHandler {
1002 public:
1003 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +02001004 : functor_(functor) {}
Danil Chapovalov89313452019-11-29 12:56:43 +01001005 void OnMessage(Message* msg) override { functor_(); }
1006
1007 private:
1008 rtc::FunctionView<void()> functor_;
1009 } handler(functor);
1010
1011 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +00001012}
1013
Tommi6866dc72020-05-15 10:11:56 +02001014// Called by the ThreadManager when being set as the current thread.
1015void Thread::EnsureIsCurrentTaskQueue() {
1016 task_queue_registration_ =
1017 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
1018}
1019
1020// Called by the ThreadManager when being set as the current thread.
1021void Thread::ClearCurrentTaskQueue() {
1022 task_queue_registration_.reset();
1023}
1024
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001025void Thread::AllowInvokesToThread(Thread* thread) {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001026#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001027 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +02001028 PostTask([thread, this]() { AllowInvokesToThread(thread); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001029 return;
1030 }
1031 RTC_DCHECK_RUN_ON(this);
1032 allowed_threads_.push_back(thread);
1033 invoke_policy_enabled_ = true;
1034#endif
1035}
1036
1037void Thread::DisallowAllInvokes() {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001038#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001039 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +02001040 PostTask([this]() { DisallowAllInvokes(); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001041 return;
1042 }
1043 RTC_DCHECK_RUN_ON(this);
1044 allowed_threads_.clear();
1045 invoke_policy_enabled_ = true;
1046#endif
1047}
1048
Tommife041642021-04-07 10:08:28 +02001049#if RTC_DCHECK_IS_ON
1050uint32_t Thread::GetBlockingCallCount() const {
1051 RTC_DCHECK_RUN_ON(this);
1052 return blocking_call_count_;
1053}
1054uint32_t Thread::GetCouldBeBlockingCallCount() const {
1055 RTC_DCHECK_RUN_ON(this);
1056 return could_be_blocking_call_count_;
1057}
1058#endif
1059
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001060// Returns true if no policies added or if there is at least one policy
Artem Titov96e3b992021-07-26 16:03:14 +02001061// that permits invocation to `target` thread.
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001062bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001063#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001064 RTC_DCHECK_RUN_ON(this);
1065 if (!invoke_policy_enabled_) {
1066 return true;
1067 }
1068 for (const auto* thread : allowed_threads_) {
1069 if (thread == target) {
1070 return true;
1071 }
1072 }
1073 return false;
1074#else
1075 return true;
1076#endif
1077}
1078
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001079void Thread::Delete() {
1080 Stop();
1081 delete this;
1082}
1083
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001084void Thread::PostTask(absl::AnyInvocable<void() &&> task) {
1085 // Though Post takes MessageData by raw pointer (last parameter), it still
1086 // takes it with ownership.
1087 Post(RTC_FROM_HERE, GetAnyInvocableMessageHandler(),
1088 /*id=*/0, new AnyInvocableMessage(std::move(task)));
1089}
1090
1091void Thread::PostDelayedTask(absl::AnyInvocable<void() &&> task,
1092 webrtc::TimeDelta delay) {
1093 // This implementation does not support low precision yet.
1094 PostDelayedHighPrecisionTask(std::move(task), delay);
1095}
1096
1097void Thread::PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
1098 webrtc::TimeDelta delay) {
1099 int delay_ms = delay.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms<int>();
1100 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1101 // it still takes it with ownership.
1102 PostDelayed(RTC_FROM_HERE, delay_ms, GetAnyInvocableMessageHandler(),
1103 /*id=*/0, new AnyInvocableMessage(std::move(task)));
1104}
1105
Niels Möller8909a632018-09-06 08:42:44 +02001106bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001107 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001108}
1109
Peter Boström0c4e06b2015-10-07 12:23:21 +02001110void Thread::Clear(MessageHandler* phandler,
1111 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001112 MessageList* removed) {
1113 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001114 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001115}
1116
1117bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001118 // Using ProcessMessages with a custom clock for testing and a time greater
1119 // than 0 doesn't work, since it's not guaranteed to advance the custom
1120 // clock's time, and may get stuck in an infinite loop.
1121 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1122 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001123 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001124 int cmsNext = cmsLoop;
1125
1126 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001127#if defined(WEBRTC_MAC)
1128 ScopedAutoReleasePool pool;
1129#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001130 Message msg;
1131 if (!Get(&msg, cmsNext))
1132 return !IsQuitting();
1133 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001134
kthelgasonde6adbe2017-02-22 00:42:11 -08001135 if (cmsLoop != kForever) {
1136 cmsNext = static_cast<int>(TimeUntil(msEnd));
1137 if (cmsNext < 0)
1138 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001139 }
1140 }
1141}
1142
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001143bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1144 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001145 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001146
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001147#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001148 if (need_synchronize_access) {
1149 // We explicitly ask for no rights other than synchronization.
1150 // This gives us the best chance of succeeding.
1151 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1152 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001153 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001154 return false;
1155 }
1156 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001157 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001158#elif defined(WEBRTC_POSIX)
1159 thread_ = pthread_self();
1160#endif
1161 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001162 thread_manager->SetCurrentThread(this);
1163 return true;
1164}
1165
Tommi51492422017-12-04 15:18:23 +01001166bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001167#if defined(WEBRTC_WIN)
1168 return thread_ != nullptr;
1169#elif defined(WEBRTC_POSIX)
1170 return thread_ != 0;
1171#endif
1172}
1173
Taylor Brandstetter08672602018-03-02 15:20:33 -08001174AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +01001175 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001176 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001177 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001178 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1179 // post a message to a queue that no running thread is serving.
1180 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001181 ThreadManager::Instance()->SetCurrentThread(this);
1182 }
1183}
1184
1185AutoThread::~AutoThread() {
1186 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001187 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001188 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001189 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001190 }
1191}
1192
nisse7eaa4ea2017-05-08 05:25:41 -07001193AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001194 : Thread(ss, /*do_init=*/false) {
1195 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001196 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001197 // Temporarily set the current thread to nullptr so that we can keep checks
1198 // around that catch unintentional pointer overwrites.
1199 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001200 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1201 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001202 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001203 }
1204}
1205
1206AutoSocketServerThread::~AutoSocketServerThread() {
1207 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
Steve Anton3b80aac2017-10-19 10:17:12 -07001208 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001209 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001210 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1211 // its contents rely on this thread still being set as the current thread.
1212 Stop();
1213 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001214 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001215 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1216 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001217 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001218 }
1219}
1220
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001221} // namespace rtc