blob: be0d15da4aee46b12484918318199f09bc706e32 [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>
28#include <utility>
Yves Gerey2e00abc2018-10-05 15:39:24 +020029
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "rtc_base/null_socket_server.h"
34#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020037#if defined(WEBRTC_MAC)
38#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020039
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020040/*
41 * These are forward-declarations for methods that are part of the
42 * ObjC runtime. They are declared in the private header objc-internal.h.
43 * These calls are what clang inserts when using @autoreleasepool in ObjC,
44 * but here they are used directly in order to keep this file C++.
45 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
46 */
47extern "C" {
48void* objc_autoreleasePoolPush(void);
49void objc_autoreleasePoolPop(void* pool);
50}
51
52namespace {
53class ScopedAutoReleasePool {
54 public:
55 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
56 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
57
58 private:
59 void* const pool_;
60};
61} // namespace
62#endif
63
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000064namespace rtc {
65
66ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +020067 static ThreadManager* const thread_manager = new ThreadManager();
68 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069}
70
nisse7866cfe2017-04-26 01:45:31 -070071ThreadManager::~ThreadManager() {
72 // By above RTC_DEFINE_STATIC_LOCAL.
73 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
74}
75
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000076// static
77Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -070078 ThreadManager* manager = ThreadManager::Instance();
79 Thread* thread = manager->CurrentThread();
80
Niels Moller9d1840c2019-05-21 07:26:37 +000081#ifndef NO_MAIN_THREAD_WRAPPING
82 // Only autowrap the thread which instantiated the ThreadManager.
83 if (!thread && manager->IsMainThread()) {
84 thread = new Thread(SocketServer::CreateDefault());
85 thread->WrapCurrentWithThreadManager(manager, true);
86 }
87#endif
88
nisse7866cfe2017-04-26 01:45:31 -070089 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090}
91
92#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +000093ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020094#if defined(WEBRTC_MAC)
95 InitCocoaMultiThreading();
96#endif
deadbeef37f5ecf2017-02-27 14:06:41 -080097 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000098}
99
Yves Gerey665174f2018-06-19 15:03:05 +0200100Thread* ThreadManager::CurrentThread() {
101 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000102}
103
Tommi6f314bb2017-12-04 20:38:20 +0100104void ThreadManager::SetCurrentThread(Thread* thread) {
105#if RTC_DLOG_IS_ON
106 if (CurrentThread() && thread) {
107 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
108 }
109#endif // RTC_DLOG_IS_ON
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000110 pthread_setspecific(key_, thread);
111}
112#endif
113
114#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000115ThreadManager::ThreadManager()
116 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200117
118Thread* ThreadManager::CurrentThread() {
119 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000120}
121
Yves Gerey665174f2018-06-19 15:03:05 +0200122void ThreadManager::SetCurrentThread(Thread* thread) {
Tommi51492422017-12-04 15:18:23 +0100123 RTC_DCHECK(!CurrentThread() || !thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124 TlsSetValue(key_, thread);
125}
126#endif
127
Yves Gerey665174f2018-06-19 15:03:05 +0200128Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800130 if (nullptr == result) {
tommie7251592017-07-14 14:44:46 -0700131 result = new Thread(SocketServer::CreateDefault());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000132 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133 }
134 return result;
135}
136
137void ThreadManager::UnwrapCurrentThread() {
138 Thread* t = CurrentThread();
139 if (t && !(t->IsOwned())) {
140 t->UnwrapCurrent();
141 delete t;
142 }
143}
144
Niels Moller9d1840c2019-05-21 07:26:37 +0000145bool ThreadManager::IsMainThread() {
146 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
147}
148
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000149Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200150 : thread_(Thread::Current()),
151 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000152
153Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800154 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000155 thread_->SetAllowBlockingCalls(previous_state_);
156}
157
Taylor Brandstetter08672602018-03-02 15:20:33 -0800158Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700159
160Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800161 : Thread(std::move(ss), /*do_init=*/true) {}
162
163Thread::Thread(SocketServer* ss, bool do_init)
164 : MessageQueue(ss, /*do_init=*/false) {
165 SetName("Thread", this); // default name
166 if (do_init) {
167 DoInit();
168 }
169}
170
171Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Tommi51492422017-12-04 15:18:23 +0100172 : MessageQueue(std::move(ss), false) {
danilchapbebf54c2016-04-28 01:32:48 -0700173 SetName("Thread", this); // default name
Taylor Brandstetter08672602018-03-02 15:20:33 -0800174 if (do_init) {
175 DoInit();
176 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177}
178
179Thread::~Thread() {
180 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800181 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182}
183
nisse7866cfe2017-04-26 01:45:31 -0700184bool Thread::IsCurrent() const {
185 return ThreadManager::Instance()->CurrentThread() == this;
186}
187
danilchapbebf54c2016-04-28 01:32:48 -0700188std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
189 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
190}
191
192std::unique_ptr<Thread> Thread::Create() {
193 return std::unique_ptr<Thread>(
194 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
195}
196
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000197bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000198 AssertBlockingIsAllowedOnCurrentThread();
199
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200#if defined(WEBRTC_WIN)
201 ::Sleep(milliseconds);
202 return true;
203#else
204 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
205 // so we use nanosleep() even though it has greater precision than necessary.
206 struct timespec ts;
207 ts.tv_sec = milliseconds / 1000;
208 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800209 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100211 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000212 return false;
213 }
214 return true;
215#endif
216}
217
218bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100219 RTC_DCHECK(!IsRunning());
220
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000221 name_ = name;
222 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200223 // The %p specifier typically produce at most 16 hex digits, possibly with a
224 // 0x prefix. But format is implementation defined, so add some margin.
225 char buf[30];
226 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000227 name_ += buf;
228 }
229 return true;
230}
231
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232bool Thread::Start(Runnable* runnable) {
Tommi51492422017-12-04 15:18:23 +0100233 RTC_DCHECK(!IsRunning());
234
235 if (IsRunning())
236 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237
André Susano Pinto02a57972016-07-22 13:30:05 +0200238 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000239
240 // Make sure that ThreadManager is created on the main thread before
241 // we start a new thread.
242 ThreadManager::Instance();
243
Tommi51492422017-12-04 15:18:23 +0100244 owned_ = true;
245
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246 ThreadInit* init = new ThreadInit;
247 init->thread = this;
248 init->runnable = runnable;
249#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800250 thread_ = CreateThread(nullptr, 0, PreRun, init, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100251 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252 return false;
253 }
254#elif defined(WEBRTC_POSIX)
255 pthread_attr_t attr;
256 pthread_attr_init(&attr);
257
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258 int error_code = pthread_create(&thread_, &attr, PreRun, init);
259 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100260 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100261 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 return false;
263 }
Tommi51492422017-12-04 15:18:23 +0100264 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265#endif
266 return true;
267}
268
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000269bool Thread::WrapCurrent() {
270 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
271}
272
273void Thread::UnwrapCurrent() {
274 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800275 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000276#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800277 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000278 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100279 RTC_LOG_GLE(LS_ERROR)
280 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000281 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800282 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100283 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000284 }
Tommi51492422017-12-04 15:18:23 +0100285#elif defined(WEBRTC_POSIX)
286 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000287#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000288}
289
290void Thread::SafeWrapCurrent() {
291 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
292}
293
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000294void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100295 if (!IsRunning())
296 return;
297
298 RTC_DCHECK(!IsCurrent());
299 if (Current() && !Current()->blocking_calls_allowed_) {
300 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
301 << "but blocking calls have been disallowed";
302 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000303
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000304#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100305 RTC_DCHECK(thread_ != nullptr);
306 WaitForSingleObject(thread_, INFINITE);
307 CloseHandle(thread_);
308 thread_ = nullptr;
309 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100311 pthread_join(thread_, nullptr);
312 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314}
315
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000316bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800317 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000318 bool previous = blocking_calls_allowed_;
319 blocking_calls_allowed_ = allow;
320 return previous;
321}
322
323// static
324void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700325#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000326 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800327 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000328#endif
329}
330
deadbeefdc20e262017-01-31 15:10:44 -0800331// static
332#if defined(WEBRTC_WIN)
333DWORD WINAPI Thread::PreRun(LPVOID pv) {
334#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800336#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337 ThreadInit* init = static_cast<ThreadInit*>(pv);
338 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200339 rtc::SetCurrentThreadName(init->thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200340#if defined(WEBRTC_MAC)
341 ScopedAutoReleasePool pool;
342#endif
kthelgasonde6adbe2017-02-22 00:42:11 -0800343 if (init->runnable) {
344 init->runnable->Run(init->thread);
345 } else {
346 init->thread->Run();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000347 }
Tommi51492422017-12-04 15:18:23 +0100348 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800349 delete init;
350#ifdef WEBRTC_WIN
351 return 0;
352#else
353 return nullptr;
354#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355}
356
357void Thread::Run() {
358 ProcessMessages(kForever);
359}
360
361bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100362 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000363 return owned_;
364}
365
366void Thread::Stop() {
367 MessageQueue::Quit();
368 Join();
369}
370
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700371void Thread::Send(const Location& posted_from,
372 MessageHandler* phandler,
373 uint32_t id,
374 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200375 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000376 return;
377
378 // Sent messages are sent to the MessageHandler directly, in the context
379 // of "thread", like Win32 SendMessage. If in the right context,
380 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000381 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700382 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000383 msg.phandler = phandler;
384 msg.message_id = id;
385 msg.pdata = pdata;
386 if (IsCurrent()) {
387 phandler->OnMessage(&msg);
388 return;
389 }
390
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000391 AssertBlockingIsAllowedOnCurrentThread();
392
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000393 AutoThread thread;
Yves Gerey665174f2018-06-19 15:03:05 +0200394 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800395 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000396
397 bool ready = false;
398 {
399 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000400 _SendMessage smsg;
401 smsg.thread = current_thread;
402 smsg.msg = msg;
403 smsg.ready = &ready;
404 sendlist_.push_back(smsg);
405 }
406
407 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800408 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000409
410 bool waited = false;
411 crit_.Enter();
412 while (!ready) {
413 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000414 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
415 // thread invoking calls on the current thread.
416 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000417 current_thread->socketserver()->Wait(kForever, false);
418 waited = true;
419 crit_.Enter();
420 }
421 crit_.Leave();
422
423 // Our Wait loop above may have consumed some WakeUp events for this
424 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
425 // cause problems for some SocketServers.
426 //
427 // Concrete example:
428 // Win32SocketServer on thread A calls Send on thread B. While processing the
429 // message, thread B Posts a message to A. We consume the wakeup for that
430 // Post while waiting for the Send to complete, which means that when we exit
431 // this loop, we need to issue another WakeUp, or else the Posted message
432 // won't be processed in a timely manner.
433
434 if (waited) {
435 current_thread->socketserver()->WakeUp();
436 }
437}
438
439void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800440 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000441}
442
443void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000444 // Receive a sent message. Cleanup scenarios:
445 // - thread sending exits: We don't allow this, since thread can exit
446 // only via Join, so Send must complete.
447 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
448 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000449 _SendMessage smsg;
450
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000451 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000452 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000453 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000454
Ishan Khota3b66012018-06-26 20:04:43 -0700455 Dispatch(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000456
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000457 crit_.Enter();
458 *smsg.ready = true;
459 smsg.thread->socketserver()->WakeUp();
460 }
461 crit_.Leave();
462}
463
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000464bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
465 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
466 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800467 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000468 *msg = *it;
469 sendlist_.erase(it);
470 return true;
471 }
472 }
473 return false;
474}
475
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700476void Thread::InvokeInternal(const Location& posted_from,
477 MessageHandler* handler) {
478 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
479 posted_from.file_and_line(), "src_func",
480 posted_from.function_name());
481 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000482}
483
Niels Möller8909a632018-09-06 08:42:44 +0200484bool Thread::IsProcessingMessagesForTesting() {
485 return (owned_ || IsCurrent()) &&
486 MessageQueue::IsProcessingMessagesForTesting();
487}
488
Peter Boström0c4e06b2015-10-07 12:23:21 +0200489void Thread::Clear(MessageHandler* phandler,
490 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000491 MessageList* removed) {
492 CritScope cs(&crit_);
493
494 // Remove messages on sendlist_ with phandler
495 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800496 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000497
498 std::list<_SendMessage>::iterator iter = sendlist_.begin();
499 while (iter != sendlist_.end()) {
500 _SendMessage smsg = *iter;
501 if (smsg.msg.Match(phandler, id)) {
502 if (removed) {
503 removed->push_back(smsg.msg);
504 } else {
505 delete smsg.msg.pdata;
506 }
507 iter = sendlist_.erase(iter);
508 *smsg.ready = true;
509 smsg.thread->socketserver()->WakeUp();
510 continue;
511 }
512 ++iter;
513 }
514
Niels Möller5e007b72018-09-07 12:35:44 +0200515 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000516}
517
518bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700519 // Using ProcessMessages with a custom clock for testing and a time greater
520 // than 0 doesn't work, since it's not guaranteed to advance the custom
521 // clock's time, and may get stuck in an infinite loop.
522 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
523 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700524 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000525 int cmsNext = cmsLoop;
526
527 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200528#if defined(WEBRTC_MAC)
529 ScopedAutoReleasePool pool;
530#endif
kthelgasonde6adbe2017-02-22 00:42:11 -0800531 Message msg;
532 if (!Get(&msg, cmsNext))
533 return !IsQuitting();
534 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535
kthelgasonde6adbe2017-02-22 00:42:11 -0800536 if (cmsLoop != kForever) {
537 cmsNext = static_cast<int>(TimeUntil(msEnd));
538 if (cmsNext < 0)
539 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000540 }
541 }
542}
543
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000544bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
545 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100546 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000547
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000548#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000549 if (need_synchronize_access) {
550 // We explicitly ask for no rights other than synchronization.
551 // This gives us the best chance of succeeding.
552 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
553 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100554 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000555 return false;
556 }
557 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000558 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000559#elif defined(WEBRTC_POSIX)
560 thread_ = pthread_self();
561#endif
562 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000563 thread_manager->SetCurrentThread(this);
564 return true;
565}
566
Tommi51492422017-12-04 15:18:23 +0100567bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +0100568#if defined(WEBRTC_WIN)
569 return thread_ != nullptr;
570#elif defined(WEBRTC_POSIX)
571 return thread_ != 0;
572#endif
573}
574
Taylor Brandstetter08672602018-03-02 15:20:33 -0800575AutoThread::AutoThread()
576 : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
Niels Moller9d1840c2019-05-21 07:26:37 +0000577 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000578 if (!ThreadManager::Instance()->CurrentThread()) {
579 ThreadManager::Instance()->SetCurrentThread(this);
580 }
581}
582
583AutoThread::~AutoThread() {
584 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700585 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000586 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800587 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000588 }
589}
590
nisse7eaa4ea2017-05-08 05:25:41 -0700591AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800592 : Thread(ss, /*do_init=*/false) {
593 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -0700594 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100595 // Temporarily set the current thread to nullptr so that we can keep checks
596 // around that catch unintentional pointer overwrites.
597 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700598 rtc::ThreadManager::Instance()->SetCurrentThread(this);
599 if (old_thread_) {
600 MessageQueueManager::Remove(old_thread_);
601 }
602}
603
604AutoSocketServerThread::~AutoSocketServerThread() {
605 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
606 // Some tests post destroy messages to this thread. To avoid memory
607 // leaks, we have to process those messages. In particular
608 // P2PTransportChannelPingTest, relying on the message posted in
609 // cricket::Connection::Destroy.
610 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -0700611 // Stop and destroy the thread before clearing it as the current thread.
612 // Sometimes there are messages left in the MessageQueue that will be
613 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
614 // its contents rely on this thread still being set as the current thread.
615 Stop();
616 DoDestroy();
Tommi51492422017-12-04 15:18:23 +0100617 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700618 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
619 if (old_thread_) {
620 MessageQueueManager::Add(old_thread_);
621 }
622}
623
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000624} // namespace rtc