blob: 4dd5fd2224f12a6aaeb52ae81cfb845b2bdb4885 [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"
Yves Gerey988cc082018-10-23 12:03:01 +020031#include "rtc_base/criticalsection.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/logging.h"
33#include "rtc_base/nullsocketserver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/timeutils.h"
35#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
81#ifndef NO_MAIN_THREAD_WRAPPING
82 // Only autowrap the thread which instantiated the ThreadManager.
83 if (!thread && manager->IsMainThread()) {
tommie7251592017-07-14 14:44:46 -070084 thread = new Thread(SocketServer::CreateDefault());
nisse7866cfe2017-04-26 01:45:31 -070085 thread->WrapCurrentWithThreadManager(manager, true);
86 }
87#endif
88
89 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090}
91
92#if defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +010093ThreadManager::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)
Tommi51492422017-12-04 15:18:23 +0100115ThreadManager::ThreadManager()
Yves Gerey665174f2018-06-19 15:03:05 +0200116 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
117
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
nisse7866cfe2017-04-26 01:45:31 -0700145bool 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
tommie7251592017-07-14 14:44:46 -0700158// DEPRECATED.
danilchapbebf54c2016-04-28 01:32:48 -0700159Thread::Thread() : Thread(SocketServer::CreateDefault()) {}
160
Taylor Brandstetter08672602018-03-02 15:20:33 -0800161Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700162
163Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800164 : Thread(std::move(ss), /*do_init=*/true) {}
165
166Thread::Thread(SocketServer* ss, bool do_init)
167 : MessageQueue(ss, /*do_init=*/false) {
168 SetName("Thread", this); // default name
169 if (do_init) {
170 DoInit();
171 }
172}
173
174Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Tommi51492422017-12-04 15:18:23 +0100175 : MessageQueue(std::move(ss), false) {
danilchapbebf54c2016-04-28 01:32:48 -0700176 SetName("Thread", this); // default name
Taylor Brandstetter08672602018-03-02 15:20:33 -0800177 if (do_init) {
178 DoInit();
179 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180}
181
182Thread::~Thread() {
183 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800184 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185}
186
nisse7866cfe2017-04-26 01:45:31 -0700187bool Thread::IsCurrent() const {
188 return ThreadManager::Instance()->CurrentThread() == this;
189}
190
danilchapbebf54c2016-04-28 01:32:48 -0700191std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
192 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
193}
194
195std::unique_ptr<Thread> Thread::Create() {
196 return std::unique_ptr<Thread>(
197 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
198}
199
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000201 AssertBlockingIsAllowedOnCurrentThread();
202
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000203#if defined(WEBRTC_WIN)
204 ::Sleep(milliseconds);
205 return true;
206#else
207 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
208 // so we use nanosleep() even though it has greater precision than necessary.
209 struct timespec ts;
210 ts.tv_sec = milliseconds / 1000;
211 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800212 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100214 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215 return false;
216 }
217 return true;
218#endif
219}
220
221bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100222 RTC_DCHECK(!IsRunning());
223
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000224 name_ = name;
225 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200226 // The %p specifier typically produce at most 16 hex digits, possibly with a
227 // 0x prefix. But format is implementation defined, so add some margin.
228 char buf[30];
229 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000230 name_ += buf;
231 }
232 return true;
233}
234
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000235bool Thread::Start(Runnable* runnable) {
Tommi51492422017-12-04 15:18:23 +0100236 RTC_DCHECK(!IsRunning());
237
238 if (IsRunning())
239 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240
André Susano Pinto02a57972016-07-22 13:30:05 +0200241 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242
243 // Make sure that ThreadManager is created on the main thread before
244 // we start a new thread.
245 ThreadManager::Instance();
246
Tommi51492422017-12-04 15:18:23 +0100247 owned_ = true;
248
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249 ThreadInit* init = new ThreadInit;
250 init->thread = this;
251 init->runnable = runnable;
252#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800253 thread_ = CreateThread(nullptr, 0, PreRun, init, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100254 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255 return false;
256 }
257#elif defined(WEBRTC_POSIX)
258 pthread_attr_t attr;
259 pthread_attr_init(&attr);
260
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261 int error_code = pthread_create(&thread_, &attr, PreRun, init);
262 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100263 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100264 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265 return false;
266 }
Tommi51492422017-12-04 15:18:23 +0100267 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000268#endif
269 return true;
270}
271
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000272bool Thread::WrapCurrent() {
273 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
274}
275
276void Thread::UnwrapCurrent() {
277 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800278 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000279#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800280 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000281 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100282 RTC_LOG_GLE(LS_ERROR)
283 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000284 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800285 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100286 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000287 }
Tommi51492422017-12-04 15:18:23 +0100288#elif defined(WEBRTC_POSIX)
289 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000290#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000291}
292
293void Thread::SafeWrapCurrent() {
294 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
295}
296
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000297void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100298 if (!IsRunning())
299 return;
300
301 RTC_DCHECK(!IsCurrent());
302 if (Current() && !Current()->blocking_calls_allowed_) {
303 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
304 << "but blocking calls have been disallowed";
305 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000306
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100308 RTC_DCHECK(thread_ != nullptr);
309 WaitForSingleObject(thread_, INFINITE);
310 CloseHandle(thread_);
311 thread_ = nullptr;
312 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100314 pthread_join(thread_, nullptr);
315 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000317}
318
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000319bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800320 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000321 bool previous = blocking_calls_allowed_;
322 blocking_calls_allowed_ = allow;
323 return previous;
324}
325
326// static
327void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700328#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000329 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800330 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000331#endif
332}
333
deadbeefdc20e262017-01-31 15:10:44 -0800334// static
335#if defined(WEBRTC_WIN)
336DWORD WINAPI Thread::PreRun(LPVOID pv) {
337#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000338void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800339#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000340 ThreadInit* init = static_cast<ThreadInit*>(pv);
341 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200342 rtc::SetCurrentThreadName(init->thread->name_.c_str());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200343#if defined(WEBRTC_MAC)
344 ScopedAutoReleasePool pool;
345#endif
kthelgasonde6adbe2017-02-22 00:42:11 -0800346 if (init->runnable) {
347 init->runnable->Run(init->thread);
348 } else {
349 init->thread->Run();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350 }
Tommi51492422017-12-04 15:18:23 +0100351 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800352 delete init;
353#ifdef WEBRTC_WIN
354 return 0;
355#else
356 return nullptr;
357#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000358}
359
360void Thread::Run() {
361 ProcessMessages(kForever);
362}
363
364bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100365 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000366 return owned_;
367}
368
369void Thread::Stop() {
370 MessageQueue::Quit();
371 Join();
372}
373
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700374void Thread::Send(const Location& posted_from,
375 MessageHandler* phandler,
376 uint32_t id,
377 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200378 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000379 return;
380
381 // Sent messages are sent to the MessageHandler directly, in the context
382 // of "thread", like Win32 SendMessage. If in the right context,
383 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000384 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700385 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000386 msg.phandler = phandler;
387 msg.message_id = id;
388 msg.pdata = pdata;
389 if (IsCurrent()) {
390 phandler->OnMessage(&msg);
391 return;
392 }
393
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000394 AssertBlockingIsAllowedOnCurrentThread();
395
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000396 AutoThread thread;
Yves Gerey665174f2018-06-19 15:03:05 +0200397 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800398 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000399
400 bool ready = false;
401 {
402 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000403 _SendMessage smsg;
404 smsg.thread = current_thread;
405 smsg.msg = msg;
406 smsg.ready = &ready;
407 sendlist_.push_back(smsg);
408 }
409
410 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800411 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412
413 bool waited = false;
414 crit_.Enter();
415 while (!ready) {
416 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000417 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
418 // thread invoking calls on the current thread.
419 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000420 current_thread->socketserver()->Wait(kForever, false);
421 waited = true;
422 crit_.Enter();
423 }
424 crit_.Leave();
425
426 // Our Wait loop above may have consumed some WakeUp events for this
427 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
428 // cause problems for some SocketServers.
429 //
430 // Concrete example:
431 // Win32SocketServer on thread A calls Send on thread B. While processing the
432 // message, thread B Posts a message to A. We consume the wakeup for that
433 // Post while waiting for the Send to complete, which means that when we exit
434 // this loop, we need to issue another WakeUp, or else the Posted message
435 // won't be processed in a timely manner.
436
437 if (waited) {
438 current_thread->socketserver()->WakeUp();
439 }
440}
441
442void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800443 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000444}
445
446void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447 // Receive a sent message. Cleanup scenarios:
448 // - thread sending exits: We don't allow this, since thread can exit
449 // only via Join, so Send must complete.
450 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
451 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000452 _SendMessage smsg;
453
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000454 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000455 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000456 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000457
Ishan Khota3b66012018-06-26 20:04:43 -0700458 Dispatch(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000459
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000460 crit_.Enter();
461 *smsg.ready = true;
462 smsg.thread->socketserver()->WakeUp();
463 }
464 crit_.Leave();
465}
466
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000467bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
468 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
469 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800470 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000471 *msg = *it;
472 sendlist_.erase(it);
473 return true;
474 }
475 }
476 return false;
477}
478
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700479void Thread::InvokeInternal(const Location& posted_from,
480 MessageHandler* handler) {
481 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
482 posted_from.file_and_line(), "src_func",
483 posted_from.function_name());
484 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000485}
486
Niels Möller8909a632018-09-06 08:42:44 +0200487bool Thread::IsProcessingMessagesForTesting() {
488 return (owned_ || IsCurrent()) &&
489 MessageQueue::IsProcessingMessagesForTesting();
490}
491
Peter Boström0c4e06b2015-10-07 12:23:21 +0200492void Thread::Clear(MessageHandler* phandler,
493 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000494 MessageList* removed) {
495 CritScope cs(&crit_);
496
497 // Remove messages on sendlist_ with phandler
498 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800499 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000500
501 std::list<_SendMessage>::iterator iter = sendlist_.begin();
502 while (iter != sendlist_.end()) {
503 _SendMessage smsg = *iter;
504 if (smsg.msg.Match(phandler, id)) {
505 if (removed) {
506 removed->push_back(smsg.msg);
507 } else {
508 delete smsg.msg.pdata;
509 }
510 iter = sendlist_.erase(iter);
511 *smsg.ready = true;
512 smsg.thread->socketserver()->WakeUp();
513 continue;
514 }
515 ++iter;
516 }
517
Niels Möller5e007b72018-09-07 12:35:44 +0200518 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000519}
520
521bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700522 // Using ProcessMessages with a custom clock for testing and a time greater
523 // than 0 doesn't work, since it's not guaranteed to advance the custom
524 // clock's time, and may get stuck in an infinite loop.
525 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
526 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700527 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000528 int cmsNext = cmsLoop;
529
530 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200531#if defined(WEBRTC_MAC)
532 ScopedAutoReleasePool pool;
533#endif
kthelgasonde6adbe2017-02-22 00:42:11 -0800534 Message msg;
535 if (!Get(&msg, cmsNext))
536 return !IsQuitting();
537 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000538
kthelgasonde6adbe2017-02-22 00:42:11 -0800539 if (cmsLoop != kForever) {
540 cmsNext = static_cast<int>(TimeUntil(msEnd));
541 if (cmsNext < 0)
542 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000543 }
544 }
545}
546
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000547bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
548 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100549 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000550
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000551#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000552 if (need_synchronize_access) {
553 // We explicitly ask for no rights other than synchronization.
554 // This gives us the best chance of succeeding.
555 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
556 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100557 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000558 return false;
559 }
560 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000561 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000562#elif defined(WEBRTC_POSIX)
563 thread_ = pthread_self();
564#endif
565 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000566 thread_manager->SetCurrentThread(this);
567 return true;
568}
569
Tommi51492422017-12-04 15:18:23 +0100570bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +0100571#if defined(WEBRTC_WIN)
572 return thread_ != nullptr;
573#elif defined(WEBRTC_POSIX)
574 return thread_ != 0;
575#endif
576}
577
Taylor Brandstetter08672602018-03-02 15:20:33 -0800578AutoThread::AutoThread()
579 : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
580 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000581 if (!ThreadManager::Instance()->CurrentThread()) {
582 ThreadManager::Instance()->SetCurrentThread(this);
583 }
584}
585
586AutoThread::~AutoThread() {
587 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700588 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000589 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800590 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000591 }
592}
593
nisse7eaa4ea2017-05-08 05:25:41 -0700594AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800595 : Thread(ss, /*do_init=*/false) {
596 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -0700597 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100598 // Temporarily set the current thread to nullptr so that we can keep checks
599 // around that catch unintentional pointer overwrites.
600 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700601 rtc::ThreadManager::Instance()->SetCurrentThread(this);
602 if (old_thread_) {
603 MessageQueueManager::Remove(old_thread_);
604 }
605}
606
607AutoSocketServerThread::~AutoSocketServerThread() {
608 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
609 // Some tests post destroy messages to this thread. To avoid memory
610 // leaks, we have to process those messages. In particular
611 // P2PTransportChannelPingTest, relying on the message posted in
612 // cricket::Connection::Destroy.
613 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -0700614 // Stop and destroy the thread before clearing it as the current thread.
615 // Sometimes there are messages left in the MessageQueue that will be
616 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
617 // its contents rely on this thread still being set as the current thread.
618 Stop();
619 DoDestroy();
Tommi51492422017-12-04 15:18:23 +0100620 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700621 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
622 if (old_thread_) {
623 MessageQueueManager::Add(old_thread_);
624 }
625}
626
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000627} // namespace rtc