blob: 56a145c7d9591c2d289576465a73674c4c63eb5c [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
kjellanderf1c5ebf2017-06-30 05:27:14 -070011#include "webrtc/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>
17#endif
18
kjellanderf1c5ebf2017-06-30 05:27:14 -070019#include "webrtc/rtc_base/checks.h"
20#include "webrtc/rtc_base/logging.h"
21#include "webrtc/rtc_base/nullsocketserver.h"
22#include "webrtc/rtc_base/platform_thread.h"
23#include "webrtc/rtc_base/stringutils.h"
24#include "webrtc/rtc_base/timeutils.h"
25#include "webrtc/rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027namespace rtc {
28
29ThreadManager* ThreadManager::Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -070030 RTC_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000031 return &thread_manager;
32}
33
nisse7866cfe2017-04-26 01:45:31 -070034ThreadManager::~ThreadManager() {
35 // By above RTC_DEFINE_STATIC_LOCAL.
36 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
37}
38
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039// static
40Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -070041 ThreadManager* manager = ThreadManager::Instance();
42 Thread* thread = manager->CurrentThread();
43
44#ifndef NO_MAIN_THREAD_WRAPPING
45 // Only autowrap the thread which instantiated the ThreadManager.
46 if (!thread && manager->IsMainThread()) {
47 thread = new Thread();
48 thread->WrapCurrentWithThreadManager(manager, true);
49 }
50#endif
51
52 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053}
54
55#if defined(WEBRTC_POSIX)
kthelgason61abe152017-03-29 02:32:36 -070056#if !defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057ThreadManager::ThreadManager() {
nisse7866cfe2017-04-26 01:45:31 -070058 main_thread_ref_ = CurrentThreadRef();
deadbeef37f5ecf2017-02-27 14:06:41 -080059 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060}
kthelgason61abe152017-03-29 02:32:36 -070061#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062
63Thread *ThreadManager::CurrentThread() {
64 return static_cast<Thread *>(pthread_getspecific(key_));
65}
66
67void ThreadManager::SetCurrentThread(Thread *thread) {
68 pthread_setspecific(key_, thread);
69}
70#endif
71
72#if defined(WEBRTC_WIN)
73ThreadManager::ThreadManager() {
nisse7866cfe2017-04-26 01:45:31 -070074 main_thread_ref_ = CurrentThreadRef();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000075 key_ = TlsAlloc();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000076}
77
78Thread *ThreadManager::CurrentThread() {
79 return static_cast<Thread *>(TlsGetValue(key_));
80}
81
82void ThreadManager::SetCurrentThread(Thread *thread) {
83 TlsSetValue(key_, thread);
84}
85#endif
86
87Thread *ThreadManager::WrapCurrentThread() {
88 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -080089 if (nullptr == result) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090 result = new Thread();
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +000091 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092 }
93 return result;
94}
95
96void ThreadManager::UnwrapCurrentThread() {
97 Thread* t = CurrentThread();
98 if (t && !(t->IsOwned())) {
99 t->UnwrapCurrent();
100 delete t;
101 }
102}
103
nisse7866cfe2017-04-26 01:45:31 -0700104bool ThreadManager::IsMainThread() {
105 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
106}
107
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000108Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
109 : thread_(Thread::Current()),
110 previous_state_(thread_->SetAllowBlockingCalls(false)) {
111}
112
113Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800114 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000115 thread_->SetAllowBlockingCalls(previous_state_);
116}
117
danilchapbebf54c2016-04-28 01:32:48 -0700118Thread::Thread() : Thread(SocketServer::CreateDefault()) {}
119
120Thread::Thread(SocketServer* ss)
jbauch25d1f282016-02-05 00:25:02 -0800121 : MessageQueue(ss, false),
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000122 running_(true, false),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000123#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800124 thread_(nullptr),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125 thread_id_(0),
126#endif
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000127 owned_(true),
128 blocking_calls_allowed_(true) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129 SetName("Thread", this); // default name
danilchapbebf54c2016-04-28 01:32:48 -0700130 DoInit();
131}
132
133Thread::Thread(std::unique_ptr<SocketServer> ss)
134 : MessageQueue(std::move(ss), false),
135 running_(true, false),
136#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800137 thread_(nullptr),
danilchapbebf54c2016-04-28 01:32:48 -0700138 thread_id_(0),
139#endif
140 owned_(true),
141 blocking_calls_allowed_(true) {
142 SetName("Thread", this); // default name
143 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144}
145
146Thread::~Thread() {
147 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800148 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000149}
150
nisse7866cfe2017-04-26 01:45:31 -0700151bool Thread::IsCurrent() const {
152 return ThreadManager::Instance()->CurrentThread() == this;
153}
154
danilchapbebf54c2016-04-28 01:32:48 -0700155std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
156 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
157}
158
159std::unique_ptr<Thread> Thread::Create() {
160 return std::unique_ptr<Thread>(
161 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
162}
163
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000165 AssertBlockingIsAllowedOnCurrentThread();
166
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167#if defined(WEBRTC_WIN)
168 ::Sleep(milliseconds);
169 return true;
170#else
171 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
172 // so we use nanosleep() even though it has greater precision than necessary.
173 struct timespec ts;
174 ts.tv_sec = milliseconds / 1000;
175 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800176 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177 if (ret != 0) {
178 LOG_ERR(LS_WARNING) << "nanosleep() returning early";
179 return false;
180 }
181 return true;
182#endif
183}
184
185bool Thread::SetName(const std::string& name, const void* obj) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000186 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187 name_ = name;
188 if (obj) {
189 char buf[16];
190 sprintfn(buf, sizeof(buf), " 0x%p", obj);
191 name_ += buf;
192 }
193 return true;
194}
195
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196bool Thread::Start(Runnable* runnable) {
nisseede5da42017-01-12 05:15:36 -0800197 RTC_DCHECK(owned_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198 if (!owned_) return false;
nisseede5da42017-01-12 05:15:36 -0800199 RTC_DCHECK(!running());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000200 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000201
André Susano Pinto02a57972016-07-22 13:30:05 +0200202 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000203
204 // Make sure that ThreadManager is created on the main thread before
205 // we start a new thread.
206 ThreadManager::Instance();
207
208 ThreadInit* init = new ThreadInit;
209 init->thread = this;
210 init->runnable = runnable;
211#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800212 thread_ = CreateThread(nullptr, 0, PreRun, init, 0, &thread_id_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213 if (thread_) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000214 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215 } else {
216 return false;
217 }
218#elif defined(WEBRTC_POSIX)
219 pthread_attr_t attr;
220 pthread_attr_init(&attr);
221
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222 int error_code = pthread_create(&thread_, &attr, PreRun, init);
223 if (0 != error_code) {
224 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
225 return false;
226 }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000227 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000228#endif
229 return true;
230}
231
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000232bool Thread::WrapCurrent() {
233 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
234}
235
236void Thread::UnwrapCurrent() {
237 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800238 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000239#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800240 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000241 if (!CloseHandle(thread_)) {
242 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
243 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800244 thread_ = nullptr;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000245 }
246#endif
247 running_.Reset();
248}
249
250void Thread::SafeWrapCurrent() {
251 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
252}
253
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254void Thread::Join() {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000255 if (running()) {
nisseede5da42017-01-12 05:15:36 -0800256 RTC_DCHECK(!IsCurrent());
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000257 if (Current() && !Current()->blocking_calls_allowed_) {
258 LOG(LS_WARNING) << "Waiting for the thread to join, "
259 << "but blocking calls have been disallowed";
260 }
261
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800263 RTC_DCHECK(thread_ != nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 WaitForSingleObject(thread_, INFINITE);
265 CloseHandle(thread_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800266 thread_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267 thread_id_ = 0;
268#elif defined(WEBRTC_POSIX)
269 void *pv;
270 pthread_join(thread_, &pv);
271#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000272 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 }
274}
275
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000276bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800277 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000278 bool previous = blocking_calls_allowed_;
279 blocking_calls_allowed_ = allow;
280 return previous;
281}
282
283// static
284void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700285#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000286 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800287 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000288#endif
289}
290
deadbeefdc20e262017-01-31 15:10:44 -0800291// static
kthelgason61abe152017-03-29 02:32:36 -0700292#if !defined(WEBRTC_MAC)
deadbeefdc20e262017-01-31 15:10:44 -0800293#if defined(WEBRTC_WIN)
294DWORD WINAPI Thread::PreRun(LPVOID pv) {
295#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000296void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800297#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000298 ThreadInit* init = static_cast<ThreadInit*>(pv);
299 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200300 rtc::SetCurrentThreadName(init->thread->name_.c_str());
kthelgasonde6adbe2017-02-22 00:42:11 -0800301 if (init->runnable) {
302 init->runnable->Run(init->thread);
303 } else {
304 init->thread->Run();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000305 }
kthelgasonde6adbe2017-02-22 00:42:11 -0800306 delete init;
307#ifdef WEBRTC_WIN
308 return 0;
309#else
310 return nullptr;
311#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000312}
kthelgason61abe152017-03-29 02:32:36 -0700313#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314
315void Thread::Run() {
316 ProcessMessages(kForever);
317}
318
319bool Thread::IsOwned() {
320 return owned_;
321}
322
323void Thread::Stop() {
324 MessageQueue::Quit();
325 Join();
326}
327
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700328void Thread::Send(const Location& posted_from,
329 MessageHandler* phandler,
330 uint32_t id,
331 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200332 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000333 return;
334
335 // Sent messages are sent to the MessageHandler directly, in the context
336 // of "thread", like Win32 SendMessage. If in the right context,
337 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000338 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700339 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000340 msg.phandler = phandler;
341 msg.message_id = id;
342 msg.pdata = pdata;
343 if (IsCurrent()) {
344 phandler->OnMessage(&msg);
345 return;
346 }
347
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000348 AssertBlockingIsAllowedOnCurrentThread();
349
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350 AutoThread thread;
351 Thread *current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800352 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000353
354 bool ready = false;
355 {
356 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000357 _SendMessage smsg;
358 smsg.thread = current_thread;
359 smsg.msg = msg;
360 smsg.ready = &ready;
361 sendlist_.push_back(smsg);
362 }
363
364 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800365 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000366
367 bool waited = false;
368 crit_.Enter();
369 while (!ready) {
370 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000371 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
372 // thread invoking calls on the current thread.
373 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000374 current_thread->socketserver()->Wait(kForever, false);
375 waited = true;
376 crit_.Enter();
377 }
378 crit_.Leave();
379
380 // Our Wait loop above may have consumed some WakeUp events for this
381 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
382 // cause problems for some SocketServers.
383 //
384 // Concrete example:
385 // Win32SocketServer on thread A calls Send on thread B. While processing the
386 // message, thread B Posts a message to A. We consume the wakeup for that
387 // Post while waiting for the Send to complete, which means that when we exit
388 // this loop, we need to issue another WakeUp, or else the Posted message
389 // won't be processed in a timely manner.
390
391 if (waited) {
392 current_thread->socketserver()->WakeUp();
393 }
394}
395
396void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800397 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000398}
399
400void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000401 // Receive a sent message. Cleanup scenarios:
402 // - thread sending exits: We don't allow this, since thread can exit
403 // only via Join, so Send must complete.
404 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
405 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000406 _SendMessage smsg;
407
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000408 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000409 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000410 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000411
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 smsg.msg.phandler->OnMessage(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000413
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000414 crit_.Enter();
415 *smsg.ready = true;
416 smsg.thread->socketserver()->WakeUp();
417 }
418 crit_.Leave();
419}
420
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000421bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
422 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
423 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800424 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000425 *msg = *it;
426 sendlist_.erase(it);
427 return true;
428 }
429 }
430 return false;
431}
432
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700433void Thread::InvokeInternal(const Location& posted_from,
434 MessageHandler* handler) {
435 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
436 posted_from.file_and_line(), "src_func",
437 posted_from.function_name());
438 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000439}
440
Peter Boström0c4e06b2015-10-07 12:23:21 +0200441void Thread::Clear(MessageHandler* phandler,
442 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000443 MessageList* removed) {
444 CritScope cs(&crit_);
445
446 // Remove messages on sendlist_ with phandler
447 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800448 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000449
450 std::list<_SendMessage>::iterator iter = sendlist_.begin();
451 while (iter != sendlist_.end()) {
452 _SendMessage smsg = *iter;
453 if (smsg.msg.Match(phandler, id)) {
454 if (removed) {
455 removed->push_back(smsg.msg);
456 } else {
457 delete smsg.msg.pdata;
458 }
459 iter = sendlist_.erase(iter);
460 *smsg.ready = true;
461 smsg.thread->socketserver()->WakeUp();
462 continue;
463 }
464 ++iter;
465 }
466
467 MessageQueue::Clear(phandler, id, removed);
468}
469
kthelgason61abe152017-03-29 02:32:36 -0700470#if !defined(WEBRTC_MAC)
471// Note that these methods have a separate implementation for mac and ios
kjellanderf1c5ebf2017-06-30 05:27:14 -0700472// defined in webrtc/rtc_base/thread_darwin.mm.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000473bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700474 // Using ProcessMessages with a custom clock for testing and a time greater
475 // than 0 doesn't work, since it's not guaranteed to advance the custom
476 // clock's time, and may get stuck in an infinite loop.
477 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
478 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700479 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000480 int cmsNext = cmsLoop;
481
482 while (true) {
kthelgasonde6adbe2017-02-22 00:42:11 -0800483 Message msg;
484 if (!Get(&msg, cmsNext))
485 return !IsQuitting();
486 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000487
kthelgasonde6adbe2017-02-22 00:42:11 -0800488 if (cmsLoop != kForever) {
489 cmsNext = static_cast<int>(TimeUntil(msEnd));
490 if (cmsNext < 0)
491 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000492 }
493 }
494}
kthelgason61abe152017-03-29 02:32:36 -0700495#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000496
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000497bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
498 bool need_synchronize_access) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000499 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000500 return false;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000501
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000502#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000503 if (need_synchronize_access) {
504 // We explicitly ask for no rights other than synchronization.
505 // This gives us the best chance of succeeding.
506 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
507 if (!thread_) {
508 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
509 return false;
510 }
511 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000513#elif defined(WEBRTC_POSIX)
514 thread_ = pthread_self();
515#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000516
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000517 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000518 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000519 thread_manager->SetCurrentThread(this);
520 return true;
521}
522
danilchapbebf54c2016-04-28 01:32:48 -0700523AutoThread::AutoThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000524 if (!ThreadManager::Instance()->CurrentThread()) {
525 ThreadManager::Instance()->SetCurrentThread(this);
526 }
527}
528
529AutoThread::~AutoThread() {
530 Stop();
531 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800532 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000533 }
534}
535
nisse7eaa4ea2017-05-08 05:25:41 -0700536AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
537 : Thread(ss) {
538 old_thread_ = ThreadManager::Instance()->CurrentThread();
539 rtc::ThreadManager::Instance()->SetCurrentThread(this);
540 if (old_thread_) {
541 MessageQueueManager::Remove(old_thread_);
542 }
543}
544
545AutoSocketServerThread::~AutoSocketServerThread() {
546 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
547 // Some tests post destroy messages to this thread. To avoid memory
548 // leaks, we have to process those messages. In particular
549 // P2PTransportChannelPingTest, relying on the message posted in
550 // cricket::Connection::Destroy.
551 ProcessMessages(0);
552 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
553 if (old_thread_) {
554 MessageQueueManager::Add(old_thread_);
555 }
556}
557
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000558} // namespace rtc