blob: 2a79d82b06acdada376b1bae62ffc5bc7904b058 [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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013#if defined(WEBRTC_WIN)
14#include <comdef.h>
15#elif defined(WEBRTC_POSIX)
16#include <time.h>
Tommi51492422017-12-04 15:18:23 +010017#else
18#error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#endif
20
Artem Titov80d02ad2018-05-21 12:20:39 +020021#if defined(WEBRTC_WIN)
22// Disable warning that we don't care about:
23// warning C4722: destructor never returns, potential memory leak
24#pragma warning(disable : 4722)
25#endif
26
Yves Gerey988cc082018-10-23 12:03:01 +020027#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020028
Yves Gerey988cc082018-10-23 12:03:01 +020029#include <utility>
Yves Gerey2e00abc2018-10-05 15:39:24 +020030
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010031#include "absl/algorithm/container.h"
Artem Titovd15a5752021-02-10 14:31:24 +010032#include "api/sequence_checker.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010033#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020035#include "rtc_base/deprecated/recursive_critical_section.h"
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +020036#include "rtc_base/event.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010037#include "rtc_base/internal/default_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "rtc_base/null_socket_server.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010040#include "rtc_base/task_utils/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020044#if defined(WEBRTC_MAC)
45#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020046
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020047/*
48 * These are forward-declarations for methods that are part of the
49 * ObjC runtime. They are declared in the private header objc-internal.h.
50 * These calls are what clang inserts when using @autoreleasepool in ObjC,
51 * but here they are used directly in order to keep this file C++.
52 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
53 */
54extern "C" {
55void* objc_autoreleasePoolPush(void);
56void objc_autoreleasePoolPop(void* pool);
57}
58
59namespace {
60class ScopedAutoReleasePool {
61 public:
62 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
63 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
64
65 private:
66 void* const pool_;
67};
68} // namespace
69#endif
70
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080072namespace {
73
74class MessageHandlerWithTask final : public MessageHandler {
75 public:
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +020076 MessageHandlerWithTask() {}
Steve Antonbcc1a762019-12-11 11:21:53 -080077
Byoungchan Lee14af7622022-01-12 05:24:58 +090078 MessageHandlerWithTask(const MessageHandlerWithTask&) = delete;
79 MessageHandlerWithTask& operator=(const MessageHandlerWithTask&) = delete;
80
Steve Antonbcc1a762019-12-11 11:21:53 -080081 void OnMessage(Message* msg) override {
82 static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
83 delete msg->pdata;
84 }
85
86 private:
87 ~MessageHandlerWithTask() override {}
Steve Antonbcc1a762019-12-11 11:21:53 -080088};
89
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010090class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
91 public:
Markus Handell3cb525b2020-07-16 16:16:09 +020092 MarkProcessingCritScope(const RecursiveCriticalSection* cs,
93 size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010094 : cs_(cs), processing_(processing) {
95 cs_->Enter();
96 *processing_ += 1;
97 }
98
99 ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
100 *processing_ -= 1;
101 cs_->Leave();
102 }
103
Byoungchan Lee14af7622022-01-12 05:24:58 +0900104 MarkProcessingCritScope(const MarkProcessingCritScope&) = delete;
105 MarkProcessingCritScope& operator=(const MarkProcessingCritScope&) = delete;
106
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100107 private:
Markus Handell3cb525b2020-07-16 16:16:09 +0200108 const RecursiveCriticalSection* const cs_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100109 size_t* processing_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100110};
111
Steve Antonbcc1a762019-12-11 11:21:53 -0800112} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000113
114ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200115 static ThreadManager* const thread_manager = new ThreadManager();
116 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000117}
118
nisse7866cfe2017-04-26 01:45:31 -0700119ThreadManager::~ThreadManager() {
120 // By above RTC_DEFINE_STATIC_LOCAL.
Artem Titovd3251962021-11-15 16:57:07 +0100121 RTC_DCHECK_NOTREACHED() << "ThreadManager should never be destructed.";
nisse7866cfe2017-04-26 01:45:31 -0700122}
123
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124// static
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100125void ThreadManager::Add(Thread* message_queue) {
126 return Instance()->AddInternal(message_queue);
127}
128void ThreadManager::AddInternal(Thread* message_queue) {
129 CritScope cs(&crit_);
130 // Prevent changes while the list of message queues is processed.
131 RTC_DCHECK_EQ(processing_, 0);
132 message_queues_.push_back(message_queue);
133}
134
135// static
136void ThreadManager::Remove(Thread* message_queue) {
137 return Instance()->RemoveInternal(message_queue);
138}
139void ThreadManager::RemoveInternal(Thread* message_queue) {
140 {
141 CritScope cs(&crit_);
142 // Prevent changes while the list of message queues is processed.
143 RTC_DCHECK_EQ(processing_, 0);
144 std::vector<Thread*>::iterator iter;
145 iter = absl::c_find(message_queues_, message_queue);
146 if (iter != message_queues_.end()) {
147 message_queues_.erase(iter);
148 }
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100149#if RTC_DCHECK_IS_ON
150 RemoveFromSendGraph(message_queue);
151#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100152 }
153}
154
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100155#if RTC_DCHECK_IS_ON
156void ThreadManager::RemoveFromSendGraph(Thread* thread) {
157 for (auto it = send_graph_.begin(); it != send_graph_.end();) {
158 if (it->first == thread) {
159 it = send_graph_.erase(it);
160 } else {
161 it->second.erase(thread);
162 ++it;
163 }
164 }
165}
166
167void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
168 Thread* target) {
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200169 RTC_DCHECK(source);
170 RTC_DCHECK(target);
171
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100172 CritScope cs(&crit_);
173 std::deque<Thread*> all_targets({target});
174 // We check the pre-existing who-sends-to-who graph for any path from target
175 // to source. This loop is guaranteed to terminate because per the send graph
176 // invariant, there are no cycles in the graph.
Jianjun Zhuc33eeab2020-05-26 17:43:17 +0800177 for (size_t i = 0; i < all_targets.size(); i++) {
178 const auto& targets = send_graph_[all_targets[i]];
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100179 all_targets.insert(all_targets.end(), targets.begin(), targets.end());
180 }
181 RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
182 << " send loop between " << source->name() << " and " << target->name();
183
184 // We may now insert source -> target without creating a cycle, since there
185 // was no path from target to source per the prior CHECK.
186 send_graph_[source].insert(target);
187}
188#endif
189
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100190// static
191void ThreadManager::Clear(MessageHandler* handler) {
192 return Instance()->ClearInternal(handler);
193}
194void ThreadManager::ClearInternal(MessageHandler* handler) {
195 // Deleted objects may cause re-entrant calls to ClearInternal. This is
196 // allowed as the list of message queues does not change while queues are
197 // cleared.
198 MarkProcessingCritScope cs(&crit_, &processing_);
199 for (Thread* queue : message_queues_) {
200 queue->Clear(handler);
201 }
202}
203
204// static
205void ThreadManager::ProcessAllMessageQueuesForTesting() {
206 return Instance()->ProcessAllMessageQueuesInternal();
207}
208
209void ThreadManager::ProcessAllMessageQueuesInternal() {
210 // This works by posting a delayed message at the current time and waiting
211 // for it to be dispatched on all queues, which will ensure that all messages
212 // that came before it were also dispatched.
213 volatile int queues_not_done = 0;
214
215 // This class is used so that whether the posted message is processed, or the
216 // message queue is simply cleared, queues_not_done gets decremented.
217 class ScopedIncrement : public MessageData {
218 public:
219 ScopedIncrement(volatile int* value) : value_(value) {
220 AtomicOps::Increment(value_);
221 }
222 ~ScopedIncrement() override { AtomicOps::Decrement(value_); }
223
224 private:
225 volatile int* value_;
226 };
227
228 {
229 MarkProcessingCritScope cs(&crit_, &processing_);
230 for (Thread* queue : message_queues_) {
231 if (!queue->IsProcessingMessagesForTesting()) {
232 // If the queue is not processing messages, it can
233 // be ignored. If we tried to post a message to it, it would be dropped
234 // or ignored.
235 continue;
236 }
237 queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
238 new ScopedIncrement(&queues_not_done));
239 }
240 }
241
242 rtc::Thread* current = rtc::Thread::Current();
243 // Note: One of the message queues may have been on this thread, which is
244 // why we can't synchronously wait for queues_not_done to go to 0; we need
245 // to process messages as well.
246 while (AtomicOps::AcquireLoad(&queues_not_done) > 0) {
247 if (current) {
248 current->ProcessMessages(0);
249 }
250 }
251}
252
253// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -0700255 ThreadManager* manager = ThreadManager::Instance();
256 Thread* thread = manager->CurrentThread();
257
Niels Moller9d1840c2019-05-21 07:26:37 +0000258#ifndef NO_MAIN_THREAD_WRAPPING
259 // Only autowrap the thread which instantiated the ThreadManager.
260 if (!thread && manager->IsMainThread()) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100261 thread = new Thread(CreateDefaultSocketServer());
Niels Moller9d1840c2019-05-21 07:26:37 +0000262 thread->WrapCurrentWithThreadManager(manager, true);
263 }
264#endif
265
nisse7866cfe2017-04-26 01:45:31 -0700266 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267}
268
269#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +0000270ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200271#if defined(WEBRTC_MAC)
272 InitCocoaMultiThreading();
273#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800274 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275}
276
Yves Gerey665174f2018-06-19 15:03:05 +0200277Thread* ThreadManager::CurrentThread() {
278 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000279}
280
Sebastian Jansson178a6852020-01-14 11:12:26 +0100281void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282 pthread_setspecific(key_, thread);
283}
284#endif
285
286#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000287ThreadManager::ThreadManager()
288 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200289
290Thread* ThreadManager::CurrentThread() {
291 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292}
293
Sebastian Jansson178a6852020-01-14 11:12:26 +0100294void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295 TlsSetValue(key_, thread);
296}
297#endif
298
Sebastian Jansson178a6852020-01-14 11:12:26 +0100299void ThreadManager::SetCurrentThread(Thread* thread) {
300#if RTC_DLOG_IS_ON
301 if (CurrentThread() && thread) {
302 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
303 }
304#endif // RTC_DLOG_IS_ON
Tommi6866dc72020-05-15 10:11:56 +0200305
306 if (thread) {
307 thread->EnsureIsCurrentTaskQueue();
308 } else {
309 Thread* current = CurrentThread();
310 if (current) {
311 // The current thread is being cleared, e.g. as a result of
312 // UnwrapCurrent() being called or when a thread is being stopped
313 // (see PreRun()). This signals that the Thread instance is being detached
314 // from the thread, which also means that TaskQueue::Current() must not
315 // return a pointer to the Thread instance.
316 current->ClearCurrentTaskQueue();
317 }
318 }
319
Sebastian Jansson178a6852020-01-14 11:12:26 +0100320 SetCurrentThreadInternal(thread);
321}
322
323void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
324 SetCurrentThreadInternal(thread);
325}
326
Yves Gerey665174f2018-06-19 15:03:05 +0200327Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000328 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800329 if (nullptr == result) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100330 result = new Thread(CreateDefaultSocketServer());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000331 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000332 }
333 return result;
334}
335
336void ThreadManager::UnwrapCurrentThread() {
337 Thread* t = CurrentThread();
338 if (t && !(t->IsOwned())) {
339 t->UnwrapCurrent();
340 delete t;
341 }
342}
343
Niels Moller9d1840c2019-05-21 07:26:37 +0000344bool ThreadManager::IsMainThread() {
345 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
346}
347
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000348Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200349 : thread_(Thread::Current()),
350 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000351
352Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800353 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000354 thread_->SetAllowBlockingCalls(previous_state_);
355}
356
Tommife041642021-04-07 10:08:28 +0200357#if RTC_DCHECK_IS_ON
358Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls(
359 std::function<void(uint32_t, uint32_t)> callback)
360 : thread_(Thread::Current()),
361 base_blocking_call_count_(thread_->GetBlockingCallCount()),
362 base_could_be_blocking_call_count_(
363 thread_->GetCouldBeBlockingCallCount()),
364 result_callback_(std::move(callback)) {}
365
366Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() {
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200367 if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) {
368 result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount());
369 }
Tommife041642021-04-07 10:08:28 +0200370}
371
372uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const {
373 return thread_->GetBlockingCallCount() - base_blocking_call_count_;
374}
375
376uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const {
377 return thread_->GetCouldBeBlockingCallCount() -
378 base_could_be_blocking_call_count_;
379}
380
381uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const {
382 return GetBlockingCallCount() + GetCouldBeBlockingCallCount();
383}
384#endif
385
Taylor Brandstetter08672602018-03-02 15:20:33 -0800386Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700387
388Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800389 : Thread(std::move(ss), /*do_init=*/true) {}
390
391Thread::Thread(SocketServer* ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100392 : fPeekKeep_(false),
Sebastian Jansson61380c02020-01-17 14:46:08 +0100393 delayed_next_num_(0),
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100394 fInitialized_(false),
395 fDestroyed_(false),
396 stop_(0),
397 ss_(ss) {
398 RTC_DCHECK(ss);
399 ss_->SetMessageQueue(this);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800400 SetName("Thread", this); // default name
401 if (do_init) {
402 DoInit();
403 }
404}
405
406Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100407 : Thread(ss.get(), do_init) {
408 own_ss_ = std::move(ss);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000409}
410
411Thread::~Thread() {
412 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800413 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000414}
415
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100416void Thread::DoInit() {
417 if (fInitialized_) {
418 return;
419 }
420
421 fInitialized_ = true;
422 ThreadManager::Add(this);
423}
424
425void Thread::DoDestroy() {
426 if (fDestroyed_) {
427 return;
428 }
429
430 fDestroyed_ = true;
431 // The signal is done from here to ensure
432 // that it always gets called when the queue
433 // is going away.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100434 if (ss_) {
435 ss_->SetMessageQueue(nullptr);
436 }
Niels Möller9bd24572021-04-19 12:18:27 +0200437 ThreadManager::Remove(this);
438 ClearInternal(nullptr, MQID_ANY, nullptr);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100439}
440
441SocketServer* Thread::socketserver() {
442 return ss_;
443}
444
445void Thread::WakeUpSocketServer() {
446 ss_->WakeUp();
447}
448
449void Thread::Quit() {
450 AtomicOps::ReleaseStore(&stop_, 1);
451 WakeUpSocketServer();
452}
453
454bool Thread::IsQuitting() {
455 return AtomicOps::AcquireLoad(&stop_) != 0;
456}
457
458void Thread::Restart() {
459 AtomicOps::ReleaseStore(&stop_, 0);
460}
461
462bool Thread::Peek(Message* pmsg, int cmsWait) {
463 if (fPeekKeep_) {
464 *pmsg = msgPeek_;
465 return true;
466 }
467 if (!Get(pmsg, cmsWait))
468 return false;
469 msgPeek_ = *pmsg;
470 fPeekKeep_ = true;
471 return true;
472}
473
474bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
475 // Return and clear peek if present
476 // Always return the peek if it exists so there is Peek/Get symmetry
477
478 if (fPeekKeep_) {
479 *pmsg = msgPeek_;
480 fPeekKeep_ = false;
481 return true;
482 }
483
484 // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
485
486 int64_t cmsTotal = cmsWait;
487 int64_t cmsElapsed = 0;
488 int64_t msStart = TimeMillis();
489 int64_t msCurrent = msStart;
490 while (true) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100491 // Check for posted events
492 int64_t cmsDelayNext = kForever;
493 bool first_pass = true;
494 while (true) {
495 // All queue operations need to be locked, but nothing else in this loop
496 // (specifically handling disposed message) can happen inside the crit.
497 // Otherwise, disposed MessageHandlers will cause deadlocks.
498 {
499 CritScope cs(&crit_);
500 // On the first pass, check for delayed messages that have been
501 // triggered and calculate the next trigger time.
502 if (first_pass) {
503 first_pass = false;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100504 while (!delayed_messages_.empty()) {
505 if (msCurrent < delayed_messages_.top().run_time_ms_) {
506 cmsDelayNext =
507 TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100508 break;
509 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100510 messages_.push_back(delayed_messages_.top().msg_);
511 delayed_messages_.pop();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100512 }
513 }
514 // Pull a message off the message queue, if available.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100515 if (messages_.empty()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100516 break;
517 } else {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100518 *pmsg = messages_.front();
519 messages_.pop_front();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100520 }
521 } // crit_ is released here.
522
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100523 // If this was a dispose message, delete it and skip it.
524 if (MQID_DISPOSE == pmsg->message_id) {
525 RTC_DCHECK(nullptr == pmsg->phandler);
526 delete pmsg->pdata;
527 *pmsg = Message();
528 continue;
529 }
530 return true;
531 }
532
533 if (IsQuitting())
534 break;
535
536 // Which is shorter, the delay wait or the asked wait?
537
538 int64_t cmsNext;
539 if (cmsWait == kForever) {
540 cmsNext = cmsDelayNext;
541 } else {
542 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
543 if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
544 cmsNext = cmsDelayNext;
545 }
546
547 {
548 // Wait and multiplex in the meantime
549 if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
550 return false;
551 }
552
553 // If the specified timeout expired, return
554
555 msCurrent = TimeMillis();
556 cmsElapsed = TimeDiff(msCurrent, msStart);
557 if (cmsWait != kForever) {
558 if (cmsElapsed >= cmsWait)
559 return false;
560 }
561 }
562 return false;
563}
564
565void Thread::Post(const Location& posted_from,
566 MessageHandler* phandler,
567 uint32_t id,
568 MessageData* pdata,
569 bool time_sensitive) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100570 RTC_DCHECK(!time_sensitive);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100571 if (IsQuitting()) {
572 delete pdata;
573 return;
574 }
575
576 // Keep thread safe
577 // Add the message to the end of the queue
578 // Signal for the multiplexer to return
579
580 {
581 CritScope cs(&crit_);
582 Message msg;
583 msg.posted_from = posted_from;
584 msg.phandler = phandler;
585 msg.message_id = id;
586 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100587 messages_.push_back(msg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100588 }
589 WakeUpSocketServer();
590}
591
592void Thread::PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100593 int delay_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, delay_ms, TimeAfter(delay_ms), phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100598 pdata);
599}
600
601void Thread::PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100602 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100603 MessageHandler* phandler,
604 uint32_t id,
605 MessageData* pdata) {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100606 return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100607 pdata);
608}
609
610void Thread::DoDelayPost(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100611 int64_t delay_ms,
612 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100613 MessageHandler* phandler,
614 uint32_t id,
615 MessageData* pdata) {
616 if (IsQuitting()) {
617 delete pdata;
618 return;
619 }
620
621 // Keep thread safe
622 // Add to the priority queue. Gets sorted soonest first.
623 // Signal for the multiplexer to return.
624
625 {
626 CritScope cs(&crit_);
627 Message msg;
628 msg.posted_from = posted_from;
629 msg.phandler = phandler;
630 msg.message_id = id;
631 msg.pdata = pdata;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100632 DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
633 delayed_messages_.push(delayed);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100634 // If this message queue processes 1 message every millisecond for 50 days,
635 // we will wrap this number. Even then, only messages with identical times
636 // will be misordered, and then only briefly. This is probably ok.
Sebastian Jansson61380c02020-01-17 14:46:08 +0100637 ++delayed_next_num_;
638 RTC_DCHECK_NE(0, delayed_next_num_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100639 }
640 WakeUpSocketServer();
641}
642
643int Thread::GetDelay() {
644 CritScope cs(&crit_);
645
Sebastian Jansson61380c02020-01-17 14:46:08 +0100646 if (!messages_.empty())
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100647 return 0;
648
Sebastian Jansson61380c02020-01-17 14:46:08 +0100649 if (!delayed_messages_.empty()) {
650 int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100651 if (delay < 0)
652 delay = 0;
653 return delay;
654 }
655
656 return kForever;
657}
658
659void Thread::ClearInternal(MessageHandler* phandler,
660 uint32_t id,
661 MessageList* removed) {
662 // Remove messages with phandler
663
664 if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
665 if (removed) {
666 removed->push_back(msgPeek_);
667 } else {
668 delete msgPeek_.pdata;
669 }
670 fPeekKeep_ = false;
671 }
672
673 // Remove from ordered message queue
674
Sebastian Jansson61380c02020-01-17 14:46:08 +0100675 for (auto it = messages_.begin(); it != messages_.end();) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100676 if (it->Match(phandler, id)) {
677 if (removed) {
678 removed->push_back(*it);
679 } else {
680 delete it->pdata;
681 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100682 it = messages_.erase(it);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100683 } else {
684 ++it;
685 }
686 }
687
688 // Remove from priority queue. Not directly iterable, so use this approach
689
Sebastian Jansson61380c02020-01-17 14:46:08 +0100690 auto new_end = delayed_messages_.container().begin();
691 for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100692 if (it->msg_.Match(phandler, id)) {
693 if (removed) {
694 removed->push_back(it->msg_);
695 } else {
696 delete it->msg_.pdata;
697 }
698 } else {
699 *new_end++ = *it;
700 }
701 }
Sebastian Jansson61380c02020-01-17 14:46:08 +0100702 delayed_messages_.container().erase(new_end,
703 delayed_messages_.container().end());
704 delayed_messages_.reheap();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100705}
706
707void Thread::Dispatch(Message* pmsg) {
708 TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
709 pmsg->posted_from.file_name(), "src_func",
710 pmsg->posted_from.function_name());
Harald Alvestrandba694422021-01-27 21:52:14 +0000711 RTC_DCHECK_RUN_ON(this);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100712 int64_t start_time = TimeMillis();
713 pmsg->phandler->OnMessage(pmsg);
714 int64_t end_time = TimeMillis();
715 int64_t diff = TimeDiff(end_time, start_time);
Harald Alvestrandba694422021-01-27 21:52:14 +0000716 if (diff >= dispatch_warning_ms_) {
717 RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100718 << "ms to dispatch. Posted from: "
719 << pmsg->posted_from.ToString();
Harald Alvestrandba694422021-01-27 21:52:14 +0000720 // To avoid log spew, move the warning limit to only give warning
721 // for delays that are larger than the one observed.
722 dispatch_warning_ms_ = diff + 1;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100723 }
724}
725
nisse7866cfe2017-04-26 01:45:31 -0700726bool Thread::IsCurrent() const {
727 return ThreadManager::Instance()->CurrentThread() == this;
728}
729
danilchapbebf54c2016-04-28 01:32:48 -0700730std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100731 return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer()));
danilchapbebf54c2016-04-28 01:32:48 -0700732}
733
734std::unique_ptr<Thread> Thread::Create() {
735 return std::unique_ptr<Thread>(
736 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
737}
738
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000739bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000740 AssertBlockingIsAllowedOnCurrentThread();
741
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000742#if defined(WEBRTC_WIN)
743 ::Sleep(milliseconds);
744 return true;
745#else
746 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
747 // so we use nanosleep() even though it has greater precision than necessary.
748 struct timespec ts;
749 ts.tv_sec = milliseconds / 1000;
750 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800751 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000752 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100753 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000754 return false;
755 }
756 return true;
757#endif
758}
759
760bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100761 RTC_DCHECK(!IsRunning());
762
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000763 name_ = name;
764 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200765 // The %p specifier typically produce at most 16 hex digits, possibly with a
766 // 0x prefix. But format is implementation defined, so add some margin.
767 char buf[30];
768 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000769 name_ += buf;
770 }
771 return true;
772}
773
Harald Alvestrandba694422021-01-27 21:52:14 +0000774void Thread::SetDispatchWarningMs(int deadline) {
775 if (!IsCurrent()) {
776 PostTask(webrtc::ToQueuedTask(
777 [this, deadline]() { SetDispatchWarningMs(deadline); }));
778 return;
779 }
780 RTC_DCHECK_RUN_ON(this);
781 dispatch_warning_ms_ = deadline;
782}
783
Niels Möllerd2e50132019-06-11 09:24:14 +0200784bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100785 RTC_DCHECK(!IsRunning());
786
787 if (IsRunning())
788 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000789
André Susano Pinto02a57972016-07-22 13:30:05 +0200790 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000791
792 // Make sure that ThreadManager is created on the main thread before
793 // we start a new thread.
794 ThreadManager::Instance();
795
Tommi51492422017-12-04 15:18:23 +0100796 owned_ = true;
797
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000798#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200799 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100800 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000801 return false;
802 }
803#elif defined(WEBRTC_POSIX)
804 pthread_attr_t attr;
805 pthread_attr_init(&attr);
806
Niels Möllerd2e50132019-06-11 09:24:14 +0200807 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000808 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100809 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100810 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000811 return false;
812 }
Tommi51492422017-12-04 15:18:23 +0100813 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000814#endif
815 return true;
816}
817
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000818bool Thread::WrapCurrent() {
819 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
820}
821
822void Thread::UnwrapCurrent() {
823 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800824 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000825#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800826 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000827 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100828 RTC_LOG_GLE(LS_ERROR)
829 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000830 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800831 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100832 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000833 }
Tommi51492422017-12-04 15:18:23 +0100834#elif defined(WEBRTC_POSIX)
835 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000836#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000837}
838
839void Thread::SafeWrapCurrent() {
840 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
841}
842
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000843void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100844 if (!IsRunning())
845 return;
846
847 RTC_DCHECK(!IsCurrent());
848 if (Current() && !Current()->blocking_calls_allowed_) {
849 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100850 "but blocking calls have been disallowed";
Tommi51492422017-12-04 15:18:23 +0100851 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000852
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000853#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100854 RTC_DCHECK(thread_ != nullptr);
855 WaitForSingleObject(thread_, INFINITE);
856 CloseHandle(thread_);
857 thread_ = nullptr;
858 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000859#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100860 pthread_join(thread_, nullptr);
861 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000862#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000863}
864
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000865bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800866 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000867 bool previous = blocking_calls_allowed_;
868 blocking_calls_allowed_ = allow;
869 return previous;
870}
871
872// static
873void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700874#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000875 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800876 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000877#endif
878}
879
deadbeefdc20e262017-01-31 15:10:44 -0800880// static
881#if defined(WEBRTC_WIN)
882DWORD WINAPI Thread::PreRun(LPVOID pv) {
883#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000884void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800885#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200886 Thread* thread = static_cast<Thread*>(pv);
887 ThreadManager::Instance()->SetCurrentThread(thread);
888 rtc::SetCurrentThreadName(thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200889#if defined(WEBRTC_MAC)
890 ScopedAutoReleasePool pool;
891#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200892 thread->Run();
893
Tommi51492422017-12-04 15:18:23 +0100894 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800895#ifdef WEBRTC_WIN
896 return 0;
897#else
898 return nullptr;
899#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200900} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000901
902void Thread::Run() {
903 ProcessMessages(kForever);
904}
905
906bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100907 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000908 return owned_;
909}
910
911void Thread::Stop() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100912 Thread::Quit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000913 Join();
914}
915
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700916void Thread::Send(const Location& posted_from,
917 MessageHandler* phandler,
918 uint32_t id,
919 MessageData* pdata) {
Sebastian Jansson5d9b9642020-01-17 13:10:54 +0100920 RTC_DCHECK(!IsQuitting());
André Susano Pinto02a57972016-07-22 13:30:05 +0200921 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000922 return;
923
924 // Sent messages are sent to the MessageHandler directly, in the context
925 // of "thread", like Win32 SendMessage. If in the right context,
926 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000927 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700928 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000929 msg.phandler = phandler;
930 msg.message_id = id;
931 msg.pdata = pdata;
932 if (IsCurrent()) {
Tommife041642021-04-07 10:08:28 +0200933#if RTC_DCHECK_IS_ON
Artem Titov15737162021-05-25 11:17:07 +0200934 RTC_DCHECK(this->IsInvokeToThreadAllowed(this));
Tommife041642021-04-07 10:08:28 +0200935 RTC_DCHECK_RUN_ON(this);
936 could_be_blocking_call_count_++;
937#endif
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100938 msg.phandler->OnMessage(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000939 return;
940 }
941
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000942 AssertBlockingIsAllowedOnCurrentThread();
943
Yves Gerey665174f2018-06-19 15:03:05 +0200944 Thread* current_thread = Thread::Current();
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200945
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100946#if RTC_DCHECK_IS_ON
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200947 if (current_thread) {
Tommife041642021-04-07 10:08:28 +0200948 RTC_DCHECK_RUN_ON(current_thread);
949 current_thread->blocking_call_count_++;
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200950 RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
951 ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
952 this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000953 }
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200954#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000955
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200956 // Perhaps down the line we can get rid of this workaround and always require
957 // current_thread to be valid when Send() is called.
958 std::unique_ptr<rtc::Event> done_event;
959 if (!current_thread)
960 done_event.reset(new rtc::Event());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000961
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200962 bool ready = false;
963 PostTask(webrtc::ToQueuedTask(
964 [&msg]() mutable { msg.phandler->OnMessage(&msg); },
965 [this, &ready, current_thread, done = done_event.get()] {
966 if (current_thread) {
967 CritScope cs(&crit_);
968 ready = true;
969 current_thread->socketserver()->WakeUp();
970 } else {
971 done->Set();
972 }
973 }));
974
975 if (current_thread) {
976 bool waited = false;
977 crit_.Enter();
978 while (!ready) {
979 crit_.Leave();
980 current_thread->socketserver()->Wait(kForever, false);
981 waited = true;
982 crit_.Enter();
983 }
984 crit_.Leave();
985
986 // Our Wait loop above may have consumed some WakeUp events for this
987 // Thread, that weren't relevant to this Send. Losing these WakeUps can
988 // cause problems for some SocketServers.
989 //
990 // Concrete example:
991 // Win32SocketServer on thread A calls Send on thread B. While processing
992 // the message, thread B Posts a message to A. We consume the wakeup for
993 // that Post while waiting for the Send to complete, which means that when
994 // we exit this loop, we need to issue another WakeUp, or else the Posted
995 // message won't be processed in a timely manner.
996
997 if (waited) {
998 current_thread->socketserver()->WakeUp();
999 }
1000 } else {
1001 done_event->Wait(rtc::Event::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001002 }
1003}
1004
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001005void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +01001006 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -08001007 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
1008 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +01001009
1010 class FunctorMessageHandler : public MessageHandler {
1011 public:
1012 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +02001013 : functor_(functor) {}
Danil Chapovalov89313452019-11-29 12:56:43 +01001014 void OnMessage(Message* msg) override { functor_(); }
1015
1016 private:
1017 rtc::FunctionView<void()> functor_;
1018 } handler(functor);
1019
1020 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +00001021}
1022
Tommi6866dc72020-05-15 10:11:56 +02001023// Called by the ThreadManager when being set as the current thread.
1024void Thread::EnsureIsCurrentTaskQueue() {
1025 task_queue_registration_ =
1026 std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
1027}
1028
1029// Called by the ThreadManager when being set as the current thread.
1030void Thread::ClearCurrentTaskQueue() {
1031 task_queue_registration_.reset();
1032}
1033
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001034void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
1035 RTC_DCHECK(msg);
1036 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
Mirko Bonadei179b46b2021-07-24 21:50:24 +02001037 std::unique_ptr<webrtc::QueuedTask> task(data->Release());
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001038 // Thread expects handler to own Message::pdata when OnMessage is called
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001039 // Since MessageData is no longer needed, delete it.
1040 delete data;
1041
1042 // QueuedTask interface uses Run return value to communicate who owns the
1043 // task. false means QueuedTask took the ownership.
1044 if (!task->Run())
1045 task.release();
1046}
1047
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001048void Thread::AllowInvokesToThread(Thread* thread) {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001049#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001050 if (!IsCurrent()) {
1051 PostTask(webrtc::ToQueuedTask(
1052 [thread, this]() { AllowInvokesToThread(thread); }));
1053 return;
1054 }
1055 RTC_DCHECK_RUN_ON(this);
1056 allowed_threads_.push_back(thread);
1057 invoke_policy_enabled_ = true;
1058#endif
1059}
1060
1061void Thread::DisallowAllInvokes() {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001062#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001063 if (!IsCurrent()) {
1064 PostTask(webrtc::ToQueuedTask([this]() { DisallowAllInvokes(); }));
1065 return;
1066 }
1067 RTC_DCHECK_RUN_ON(this);
1068 allowed_threads_.clear();
1069 invoke_policy_enabled_ = true;
1070#endif
1071}
1072
Tommife041642021-04-07 10:08:28 +02001073#if RTC_DCHECK_IS_ON
1074uint32_t Thread::GetBlockingCallCount() const {
1075 RTC_DCHECK_RUN_ON(this);
1076 return blocking_call_count_;
1077}
1078uint32_t Thread::GetCouldBeBlockingCallCount() const {
1079 RTC_DCHECK_RUN_ON(this);
1080 return could_be_blocking_call_count_;
1081}
1082#endif
1083
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001084// Returns true if no policies added or if there is at least one policy
Artem Titov96e3b992021-07-26 16:03:14 +02001085// that permits invocation to `target` thread.
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001086bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
Mirko Bonadei481e3452021-07-30 13:57:25 +02001087#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +02001088 RTC_DCHECK_RUN_ON(this);
1089 if (!invoke_policy_enabled_) {
1090 return true;
1091 }
1092 for (const auto* thread : allowed_threads_) {
1093 if (thread == target) {
1094 return true;
1095 }
1096 }
1097 return false;
1098#else
1099 return true;
1100#endif
1101}
1102
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001103void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
1104 // Though Post takes MessageData by raw pointer (last parameter), it still
1105 // takes it with ownership.
1106 Post(RTC_FROM_HERE, &queued_task_handler_,
1107 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1108}
1109
1110void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
1111 uint32_t milliseconds) {
1112 // Though PostDelayed takes MessageData by raw pointer (last parameter),
1113 // it still takes it with ownership.
1114 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
1115 /*id=*/0,
1116 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1117}
1118
1119void Thread::Delete() {
1120 Stop();
1121 delete this;
1122}
1123
Niels Möller8909a632018-09-06 08:42:44 +02001124bool Thread::IsProcessingMessagesForTesting() {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001125 return (owned_ || IsCurrent()) && !IsQuitting();
Niels Möller8909a632018-09-06 08:42:44 +02001126}
1127
Peter Boström0c4e06b2015-10-07 12:23:21 +02001128void Thread::Clear(MessageHandler* phandler,
1129 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001130 MessageList* removed) {
1131 CritScope cs(&crit_);
Niels Möller5e007b72018-09-07 12:35:44 +02001132 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001133}
1134
1135bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -07001136 // Using ProcessMessages with a custom clock for testing and a time greater
1137 // than 0 doesn't work, since it's not guaranteed to advance the custom
1138 // clock's time, and may get stuck in an infinite loop.
1139 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1140 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -07001141 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001142 int cmsNext = cmsLoop;
1143
1144 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +02001145#if defined(WEBRTC_MAC)
1146 ScopedAutoReleasePool pool;
1147#endif
kthelgasonde6adbe2017-02-22 00:42:11 -08001148 Message msg;
1149 if (!Get(&msg, cmsNext))
1150 return !IsQuitting();
1151 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001152
kthelgasonde6adbe2017-02-22 00:42:11 -08001153 if (cmsLoop != kForever) {
1154 cmsNext = static_cast<int>(TimeUntil(msEnd));
1155 if (cmsNext < 0)
1156 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001157 }
1158 }
1159}
1160
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001161bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1162 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +01001163 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001164
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001165#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001166 if (need_synchronize_access) {
1167 // We explicitly ask for no rights other than synchronization.
1168 // This gives us the best chance of succeeding.
1169 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1170 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001171 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +00001172 return false;
1173 }
1174 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001175 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001176#elif defined(WEBRTC_POSIX)
1177 thread_ = pthread_self();
1178#endif
1179 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001180 thread_manager->SetCurrentThread(this);
1181 return true;
1182}
1183
Tommi51492422017-12-04 15:18:23 +01001184bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +01001185#if defined(WEBRTC_WIN)
1186 return thread_ != nullptr;
1187#elif defined(WEBRTC_POSIX)
1188 return thread_ != 0;
1189#endif
1190}
1191
Steve Antonbcc1a762019-12-11 11:21:53 -08001192// static
1193MessageHandler* Thread::GetPostTaskMessageHandler() {
1194 // Allocate at first call, never deallocate.
1195 static MessageHandler* handler = new MessageHandlerWithTask;
1196 return handler;
1197}
1198
Taylor Brandstetter08672602018-03-02 15:20:33 -08001199AutoThread::AutoThread()
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +01001200 : Thread(CreateDefaultSocketServer(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001201 if (!ThreadManager::Instance()->CurrentThread()) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001202 // DoInit registers with ThreadManager. Do that only if we intend to
Niels Möller5a8f8602019-06-12 11:30:59 +02001203 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1204 // post a message to a queue that no running thread is serving.
1205 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001206 ThreadManager::Instance()->SetCurrentThread(this);
1207 }
1208}
1209
1210AutoThread::~AutoThread() {
1211 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -07001212 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001213 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -08001214 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001215 }
1216}
1217
nisse7eaa4ea2017-05-08 05:25:41 -07001218AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -08001219 : Thread(ss, /*do_init=*/false) {
1220 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -07001221 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +01001222 // Temporarily set the current thread to nullptr so that we can keep checks
1223 // around that catch unintentional pointer overwrites.
1224 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001225 rtc::ThreadManager::Instance()->SetCurrentThread(this);
1226 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001227 ThreadManager::Remove(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001228 }
1229}
1230
1231AutoSocketServerThread::~AutoSocketServerThread() {
1232 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
1233 // Some tests post destroy messages to this thread. To avoid memory
1234 // leaks, we have to process those messages. In particular
1235 // P2PTransportChannelPingTest, relying on the message posted in
1236 // cricket::Connection::Destroy.
1237 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -07001238 // Stop and destroy the thread before clearing it as the current thread.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001239 // Sometimes there are messages left in the Thread that will be
Steve Anton3b80aac2017-10-19 10:17:12 -07001240 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1241 // its contents rely on this thread still being set as the current thread.
1242 Stop();
1243 DoDestroy();
Tommi51492422017-12-04 15:18:23 +01001244 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -07001245 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1246 if (old_thread_) {
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +01001247 ThreadManager::Add(old_thread_);
nisse7eaa4ea2017-05-08 05:25:41 -07001248 }
1249}
1250
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001251} // namespace rtc