blob: 99469896e6c9c4de196f60c54ff00e6fca6f55f0 [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)
Danil Chapovalov207f8532022-08-24 12:19:46 +0200383 : delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100384 fInitialized_(false),
385 fDestroyed_(false),
386 stop_(0),
387 ss_(ss) {
388 RTC_DCHECK(ss);
389 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800390 SetName("Thread", this); // default name
391 if (do_init) {
392 DoInit();
393 }
394}
395
396Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100397 : Thread(ss.get(), do_init) {
398 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000399}
400
401Thread::~Thread() {
402 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800403 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000404}
405
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100406void Thread::DoInit() {
407 if (fInitialized_) {
408 return;
409 }
410
411 fInitialized_ = true;
412 ThreadManager::Add(this);
413}
414
415void Thread::DoDestroy() {
416 if (fDestroyed_) {
417 return;
418 }
419
420 fDestroyed_ = true;
421 // The signal is done from here to ensure
422 // that it always gets called when the queue
423 // is going away.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100424 if (ss_) {
425 ss_->SetMessageQueue(nullptr);
426 }
Niels Möller9bd24572021-04-19 12:18:27 +0200427 ThreadManager::Remove(this);
428 ClearInternal(nullptr, MQID_ANY, nullptr);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100429}
430
431SocketServer* Thread::socketserver() {
432 return ss_;
433}
434
435void Thread::WakeUpSocketServer() {
436 ss_->WakeUp();
437}
438
439void Thread::Quit() {
Niels Möller7a669002022-06-27 09:47:02 +0200440 stop_.store(1, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100441 WakeUpSocketServer();
442}
443
444bool Thread::IsQuitting() {
Niels Möller7a669002022-06-27 09:47:02 +0200445 return stop_.load(std::memory_order_acquire) != 0;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100446}
447
448void Thread::Restart() {
Niels Möller7a669002022-06-27 09:47:02 +0200449 stop_.store(0, std::memory_order_release);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100450}
451
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100452bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100453 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
454
455 int64_t cmsTotal = cmsWait;
456 int64_t cmsElapsed = 0;
457 int64_t msStart = TimeMillis();
458 int64_t msCurrent = msStart;
459 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100460 // Check for posted events
461 int64_t cmsDelayNext = kForever;
462 bool first_pass = true;
463 while (true) {
464 // All queue operations need to be locked, but nothing else in this loop
465 // (specifically handling disposed message) can happen inside the crit.
466 // Otherwise, disposed MessageHandlers will cause deadlocks.
467 {
468 CritScope cs(&crit_);
469 // On the first pass, check for delayed messages that have been
470 // triggered and calculate the next trigger time.
471 if (first_pass) {
472 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100473 while (!delayed_messages_.empty()) {
474 if (msCurrent < delayed_messages_.top().run_time_ms_) {
475 cmsDelayNext =
476 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100477 break;
478 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100479 messages_.push_back(delayed_messages_.top().msg_);
480 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100481 }
482 }
483 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100484 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100485 break;
486 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100487 *pmsg = messages_.front();
488 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100489 }
490 } // crit_ is released here.
491
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100492 // If this was a dispose message, delete it and skip it.
493 if (MQID_DISPOSE == pmsg->message_id) {
494 RTC_DCHECK(nullptr == pmsg->phandler);
495 delete pmsg->pdata;
496 *pmsg = Message();
497 continue;
498 }
499 return true;
500 }
501
502 if (IsQuitting())
503 break;
504
505 // Which is shorter, the delay wait or the asked wait?
506
507 int64_t cmsNext;
508 if (cmsWait == kForever) {
509 cmsNext = cmsDelayNext;
510 } else {
511 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
512 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
513 cmsNext = cmsDelayNext;
514 }
515
516 {
517 // Wait and multiplex in the meantime
518 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
519 return false;
520 }
521
522 // If the specified timeout expired, return
523
524 msCurrent = TimeMillis();
525 cmsElapsed = TimeDiff(msCurrent, msStart);
526 if (cmsWait != kForever) {
527 if (cmsElapsed >= cmsWait)
528 return false;
529 }
530 }
531 return false;
532}
533
534void Thread::Post(const Location& posted_from,
535 MessageHandler* phandler,
536 uint32_t id,
537 MessageData* pdata,
538 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100539 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100540 if (IsQuitting()) {
541 delete pdata;
542 return;
543 }
544
545 // Keep thread safe
546 // Add the message to the end of the queue
547 // Signal for the multiplexer to return
548
549 {
550 CritScope cs(&crit_);
551 Message msg;
552 msg.posted_from = posted_from;
553 msg.phandler = phandler;
554 msg.message_id = id;
555 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100556 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100557 }
558 WakeUpSocketServer();
559}
560
561void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100562 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100563 MessageHandler* phandler,
564 uint32_t id,
565 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100566 return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100567 pdata);
568}
569
570void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100571 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100572 MessageHandler* phandler,
573 uint32_t id,
574 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100575 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100576 pdata);
577}
578
579void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100580 int64_t delay_ms,
581 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100582 MessageHandler* phandler,
583 uint32_t id,
584 MessageData* pdata) {
585 if (IsQuitting()) {
586 delete pdata;
587 return;
588 }
589
590 // Keep thread safe
591 // Add to the priority queue. Gets sorted soonest first.
592 // Signal for the multiplexer to return.
593
594 {
595 CritScope cs(&crit_);
596 Message msg;
597 msg.posted_from = posted_from;
598 msg.phandler = phandler;
599 msg.message_id = id;
600 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100601 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
602 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100603 // If this message queue processes 1 message every millisecond for 50 days,
604 // we will wrap this number. Even then, only messages with identical times
605 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100606 ++delayed_next_num_;
607 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100608 }
609 WakeUpSocketServer();
610}
611
612int Thread::GetDelay() {
613 CritScope cs(&crit_);
614
Sebastian Jansson61380c02020-01-17 14:46:08 +0100615 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100616 return 0;
617
Sebastian Jansson61380c02020-01-17 14:46:08 +0100618 if (!delayed_messages_.empty()) {
619 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100620 if (delay < 0)
621 delay = 0;
622 return delay;
623 }
624
625 return kForever;
626}
627
628void Thread::ClearInternal(MessageHandler* phandler,
629 uint32_t id,
630 MessageList* removed) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100631 // Remove from ordered message queue
632
Sebastian Jansson61380c02020-01-17 14:46:08 +0100633 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100634 if (it->Match(phandler, id)) {
635 if (removed) {
636 removed->push_back(*it);
637 } else {
638 delete it->pdata;
639 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100640 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100641 } else {
642 ++it;
643 }
644 }
645
646 // Remove from priority queue. Not directly iterable, so use this approach
647
Sebastian Jansson61380c02020-01-17 14:46:08 +0100648 auto new_end = delayed_messages_.container().begin();
649 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100650 if (it->msg_.Match(phandler, id)) {
651 if (removed) {
652 removed->push_back(it->msg_);
653 } else {
654 delete it->msg_.pdata;
655 }
656 } else {
657 *new_end++ = *it;
658 }
659 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100660 delayed_messages_.container().erase(new_end,
661 delayed_messages_.container().end());
662 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100663}
664
665void Thread::Dispatch(Message* pmsg) {
666 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
667 pmsg->posted_from.file_name(), "src_func",
668 pmsg->posted_from.function_name());
Harald Alvestrandba694422021-01-27 21:52:14 +0000669 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100670 int64_t start_time = TimeMillis();
671 pmsg->phandler->OnMessage(pmsg);
672 int64_t end_time = TimeMillis();
673 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000674 if (diff >= dispatch_warning_ms_) {
675 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100676 << "ms to dispatch. Posted from: "
677 << pmsg->posted_from.ToString();
Harald Alvestrandba694422021-01-27 21:52:14 +0000678 // To avoid log spew, move the warning limit to only give warning
679 // for delays that are larger than the one observed.
680 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100681 }
682}
683
nisse7866cfe2017-04-26 01:45:31 -0700684bool Thread::IsCurrent() const {
685 return ThreadManager::Instance()->CurrentThread() == this;
686}
687
danilchapbebf54c2016-04-28 01:32:48 -0700688std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100689 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700690}
691
692std::unique_ptr<Thread> Thread::Create() {
693 return std::unique_ptr<Thread>(
694 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
695}
696
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000697bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000698 AssertBlockingIsAllowedOnCurrentThread();
699
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000700#if defined(WEBRTC_WIN)
701 ::Sleep(milliseconds);
702 return true;
703#else
704 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
705 // so we use nanosleep() even though it has greater precision than necessary.
706 struct timespec ts;
707 ts.tv_sec = milliseconds / 1000;
708 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800709 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000710 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100711 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000712 return false;
713 }
714 return true;
715#endif
716}
717
Ali Tofigh7fa90572022-03-17 15:47:49 +0100718bool Thread::SetName(absl::string_view name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100719 RTC_DCHECK(!IsRunning());
720
Ali Tofigh7fa90572022-03-17 15:47:49 +0100721 name_ = std::string(name);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000722 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200723 // The %p specifier typically produce at most 16 hex digits, possibly with a
724 // 0x prefix. But format is implementation defined, so add some margin.
725 char buf[30];
726 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000727 name_ += buf;
728 }
729 return true;
730}
731
Harald Alvestrandba694422021-01-27 21:52:14 +0000732void Thread::SetDispatchWarningMs(int deadline) {
733 if (!IsCurrent()) {
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200734 PostTask([this, deadline]() { SetDispatchWarningMs(deadline); });
Harald Alvestrandba694422021-01-27 21:52:14 +0000735 return;
736 }
737 RTC_DCHECK_RUN_ON(this);
738 dispatch_warning_ms_ = deadline;
739}
740
Niels Möllerd2e50132019-06-11 09:24:14 +0200741bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100742 RTC_DCHECK(!IsRunning());
743
744 if (IsRunning())
745 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000746
André Susano Pinto02a57972016-07-22 13:30:05 +0200747 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000748
749 // Make sure that ThreadManager is created on the main thread before
750 // we start a new thread.
751 ThreadManager::Instance();
752
Tommi51492422017-12-04 15:18:23 +0100753 owned_ = true;
754
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000755#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200756 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100757 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000758 return false;
759 }
760#elif defined(WEBRTC_POSIX)
761 pthread_attr_t attr;
762 pthread_attr_init(&attr);
763
Niels Möllerd2e50132019-06-11 09:24:14 +0200764 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000765 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100766 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100767 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000768 return false;
769 }
Tommi51492422017-12-04 15:18:23 +0100770 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000771#endif
772 return true;
773}
774
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000775bool Thread::WrapCurrent() {
776 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
777}
778
779void Thread::UnwrapCurrent() {
780 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800781 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000782#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800783 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000784 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100785 RTC_LOG_GLE(LS_ERROR)
786 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000787 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800788 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100789 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000790 }
Tommi51492422017-12-04 15:18:23 +0100791#elif defined(WEBRTC_POSIX)
792 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000793#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000794}
795
796void Thread::SafeWrapCurrent() {
797 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
798}
799
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000800void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100801 if (!IsRunning())
802 return;
803
804 RTC_DCHECK(!IsCurrent());
805 if (Current() && !Current()->blocking_calls_allowed_) {
806 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100807 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100808 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000809
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000810#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100811 RTC_DCHECK(thread_ != nullptr);
812 WaitForSingleObject(thread_, INFINITE);
813 CloseHandle(thread_);
814 thread_ = nullptr;
815 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000816#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100817 pthread_join(thread_, nullptr);
818 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000819#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000820}
821
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000822bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800823 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000824 bool previous = blocking_calls_allowed_;
825 blocking_calls_allowed_ = allow;
826 return previous;
827}
828
829// static
830void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700831#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000832 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800833 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000834#endif
835}
836
deadbeefdc20e262017-01-31 15:10:44 -0800837// static
838#if defined(WEBRTC_WIN)
839DWORD WINAPI Thread::PreRun(LPVOID pv) {
840#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000841void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800842#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200843 Thread* thread = static_cast<Thread*>(pv);
844 ThreadManager::Instance()->SetCurrentThread(thread);
845 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200846#if defined(WEBRTC_MAC)
847 ScopedAutoReleasePool pool;
848#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200849 thread->Run();
850
Tommi51492422017-12-04 15:18:23 +0100851 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800852#ifdef WEBRTC_WIN
853 return 0;
854#else
855 return nullptr;
856#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200857} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000858
859void Thread::Run() {
860 ProcessMessages(kForever);
861}
862
863bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100864 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000865 return owned_;
866}
867
868void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100869 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000870 Join();
871}
872
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700873void Thread::Send(const Location& posted_from,
874 MessageHandler* phandler,
875 uint32_t id,
876 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100877 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200878 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000879 return;
880
881 // Sent messages are sent to the MessageHandler directly, in the context
882 // of "thread", like Win32 SendMessage. If in the right context,
883 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000884 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700885 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000886 msg.phandler = phandler;
887 msg.message_id = id;
888 msg.pdata = pdata;
889 if (IsCurrent()) {
Tommife041642021-04-07 10:08:28 +0200890#if RTC_DCHECK_IS_ON
Artem Titov15737162021-05-25 11:17:07 +0200891 RTC_DCHECK(this->IsInvokeToThreadAllowed(this));
Tommife041642021-04-07 10:08:28 +0200892 RTC_DCHECK_RUN_ON(this);
893 could_be_blocking_call_count_++;
894#endif
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100895 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000896 return;
897 }
898
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000899 AssertBlockingIsAllowedOnCurrentThread();
900
Yves Gerey665174f2018-06-19 15:03:05 +0200901 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200902
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100903#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200904 if (current_thread) {
Tommife041642021-04-07 10:08:28 +0200905 RTC_DCHECK_RUN_ON(current_thread);
906 current_thread->blocking_call_count_++;
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200907 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
908 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
909 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000910 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200911#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000912
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200913 // Perhaps down the line we can get rid of this workaround and always require
914 // current_thread to be valid when Send() is called.
915 std::unique_ptr<rtc::Event> done_event;
916 if (!current_thread)
917 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000918
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200919 bool ready = false;
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200920 absl::Cleanup cleanup = [this, &ready, current_thread,
921 done = done_event.get()] {
922 if (current_thread) {
923 CritScope cs(&crit_);
924 ready = true;
925 current_thread->socketserver()->WakeUp();
926 } else {
927 done->Set();
928 }
929 };
930 PostTask([&msg, cleanup = std::move(cleanup)]() mutable {
931 msg.phandler->OnMessage(&msg);
932 });
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200933 if (current_thread) {
934 bool waited = false;
935 crit_.Enter();
936 while (!ready) {
937 crit_.Leave();
938 current_thread->socketserver()->Wait(kForever, false);
939 waited = true;
940 crit_.Enter();
941 }
942 crit_.Leave();
943
944 // Our Wait loop above may have consumed some WakeUp events for this
945 // Thread, that weren't relevant to this Send. Losing these WakeUps can
946 // cause problems for some SocketServers.
947 //
948 // Concrete example:
949 // Win32SocketServer on thread A calls Send on thread B. While processing
950 // the message, thread B Posts a message to A. We consume the wakeup for
951 // that Post while waiting for the Send to complete, which means that when
952 // we exit this loop, we need to issue another WakeUp, or else the Posted
953 // message won't be processed in a timely manner.
954
955 if (waited) {
956 current_thread->socketserver()->WakeUp();
957 }
958 } else {
959 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000960 }
961}
962
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700963void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100964 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800965 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
966 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100967
968 class FunctorMessageHandler : public MessageHandler {
969 public:
970 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +0200971 : functor_(functor) {}
Danil Chapovalov89313452019-11-29 12:56:43 +0100972 void OnMessage(Message* msg) override { functor_(); }
973
974 private:
975 rtc::FunctionView<void()> functor_;
976 } handler(functor);
977
978 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000979}
980
Tommi6866dc72020-05-15 10:11:56 +0200981// Called by the ThreadManager when being set as the current thread.
982void Thread::EnsureIsCurrentTaskQueue() {
983 task_queue_registration_ =
984 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
985}
986
987// Called by the ThreadManager when being set as the current thread.
988void Thread::ClearCurrentTaskQueue() {
989 task_queue_registration_.reset();
990}
991
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200992void Thread::AllowInvokesToThread(Thread* thread) {
Mirko Bonadei481e3452021-07-30 13:57:25 +0200993#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200994 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +0200995 PostTask([thread, this]() { AllowInvokesToThread(thread); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200996 return;
997 }
998 RTC_DCHECK_RUN_ON(this);
999 allowed_threads_.push_back(thread);
1000 invoke_policy_enabled_ = true;
1001#endif
1002}
1003
1004void Thread::DisallowAllInvokes() {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001005#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001006 if (!IsCurrent()) {
Danil Chapovalov5286dcf2022-07-18 17:04:56 +02001007 PostTask([this]() { DisallowAllInvokes(); });
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001008 return;
1009 }
1010 RTC_DCHECK_RUN_ON(this);
1011 allowed_threads_.clear();
1012 invoke_policy_enabled_ = true;
1013#endif
1014}
1015
Tommife041642021-04-07 10:08:28 +02001016#if RTC_DCHECK_IS_ON
1017uint32_t Thread::GetBlockingCallCount() const {
1018 RTC_DCHECK_RUN_ON(this);
1019 return blocking_call_count_;
1020}
1021uint32_t Thread::GetCouldBeBlockingCallCount() const {
1022 RTC_DCHECK_RUN_ON(this);
1023 return could_be_blocking_call_count_;
1024}
1025#endif
1026
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001027// Returns true if no policies added or if there is at least one policy
Artem Titov96e3b992021-07-26 16:03:14 +02001028// that permits invocation to `target` thread.
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001029bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001030#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001031 RTC_DCHECK_RUN_ON(this);
1032 if (!invoke_policy_enabled_) {
1033 return true;
1034 }
1035 for (const auto* thread : allowed_threads_) {
1036 if (thread == target) {
1037 return true;
1038 }
1039 }
1040 return false;
1041#else
1042 return true;
1043#endif
1044}
1045
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001046void Thread::Delete() {
1047 Stop();
1048 delete this;
1049}
1050
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001051void Thread::PostTask(absl::AnyInvocable<void() &&> task) {
1052 // Though Post takes MessageData by raw pointer (last parameter), it still
1053 // takes it with ownership.
1054 Post(RTC_FROM_HERE, GetAnyInvocableMessageHandler(),
1055 /*id=*/0, new AnyInvocableMessage(std::move(task)));
1056}
1057
1058void Thread::PostDelayedTask(absl::AnyInvocable<void() &&> task,
1059 webrtc::TimeDelta delay) {
1060 // This implementation does not support low precision yet.
1061 PostDelayedHighPrecisionTask(std::move(task), delay);
1062}
1063
1064void Thread::PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
1065 webrtc::TimeDelta delay) {
1066 int delay_ms = delay.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms<int>();
1067 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1068 // it still takes it with ownership.
1069 PostDelayed(RTC_FROM_HERE, delay_ms, GetAnyInvocableMessageHandler(),
1070 /*id=*/0, new AnyInvocableMessage(std::move(task)));
1071}
1072
Niels Möller8909a632018-09-06 08:42:44 +02001073bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001074 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001075}
1076
Peter Boström0c4e06b2015-10-07 12:23:21 +02001077void Thread::Clear(MessageHandler* phandler,
1078 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001079 MessageList* removed) {
1080 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001081 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001082}
1083
1084bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001085 // Using ProcessMessages with a custom clock for testing and a time greater
1086 // than 0 doesn't work, since it's not guaranteed to advance the custom
1087 // clock's time, and may get stuck in an infinite loop.
1088 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1089 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001090 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001091 int cmsNext = cmsLoop;
1092
1093 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001094#if defined(WEBRTC_MAC)
1095 ScopedAutoReleasePool pool;
1096#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001097 Message msg;
1098 if (!Get(&msg, cmsNext))
1099 return !IsQuitting();
1100 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001101
kthelgasonde6adbe2017-02-22 00:42:11 -08001102 if (cmsLoop != kForever) {
1103 cmsNext = static_cast<int>(TimeUntil(msEnd));
1104 if (cmsNext < 0)
1105 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001106 }
1107 }
1108}
1109
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001110bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1111 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001112 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001113
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001114#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001115 if (need_synchronize_access) {
1116 // We explicitly ask for no rights other than synchronization.
1117 // This gives us the best chance of succeeding.
1118 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1119 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001120 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001121 return false;
1122 }
1123 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001124 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001125#elif defined(WEBRTC_POSIX)
1126 thread_ = pthread_self();
1127#endif
1128 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001129 thread_manager->SetCurrentThread(this);
1130 return true;
1131}
1132
Tommi51492422017-12-04 15:18:23 +01001133bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001134#if defined(WEBRTC_WIN)
1135 return thread_ != nullptr;
1136#elif defined(WEBRTC_POSIX)
1137 return thread_ != 0;
1138#endif
1139}
1140
Taylor Brandstetter08672602018-03-02 15:20:33 -08001141AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +01001142 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001143 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001144 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001145 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1146 // post a message to a queue that no running thread is serving.
1147 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001148 ThreadManager::Instance()->SetCurrentThread(this);
1149 }
1150}
1151
1152AutoThread::~AutoThread() {
1153 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001154 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001155 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001156 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001157 }
1158}
1159
nisse7eaa4ea2017-05-08 05:25:41 -07001160AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001161 : Thread(ss, /*do_init=*/false) {
1162 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001163 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001164 // Temporarily set the current thread to nullptr so that we can keep checks
1165 // around that catch unintentional pointer overwrites.
1166 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001167 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1168 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001169 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001170 }
1171}
1172
1173AutoSocketServerThread::~AutoSocketServerThread() {
1174 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
Steve Anton3b80aac2017-10-19 10:17:12 -07001175 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001176 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001177 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1178 // its contents rely on this thread still being set as the current thread.
1179 Stop();
1180 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001181 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001182 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1183 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001184 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001185 }
1186}
1187
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001188} // namespace rtc