blob: 591253f1913bfbaa15fb9b31d440b8b412840c98 [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
11#include "webrtc/base/thread.h"
12
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
nisseede5da42017-01-12 05:15:36 -080019#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020#include "webrtc/base/logging.h"
danilchapbebf54c2016-04-28 01:32:48 -070021#include "webrtc/base/nullsocketserver.h"
Tommiea14f0a2015-05-18 13:51:06 +020022#include "webrtc/base/platform_thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023#include "webrtc/base/stringutils.h"
24#include "webrtc/base/timeutils.h"
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070025#include "webrtc/base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026
kthelgasonde6adbe2017-02-22 00:42:11 -080027#if defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028#include "webrtc/base/maccocoathreadhelper.h"
29#include "webrtc/base/scoped_autorelease_pool.h"
30#endif
31
32namespace rtc {
33
34ThreadManager* ThreadManager::Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -070035 RTC_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036 return &thread_manager;
37}
38
39// static
40Thread* Thread::Current() {
41 return ThreadManager::Instance()->CurrentThread();
42}
43
44#if defined(WEBRTC_POSIX)
45ThreadManager::ThreadManager() {
46 pthread_key_create(&key_, NULL);
47#ifndef NO_MAIN_THREAD_WRAPPING
48 WrapCurrentThread();
49#endif
kthelgasonde6adbe2017-02-22 00:42:11 -080050#if defined(WEBRTC_MAC)
51 // This is necessary to alert the cocoa runtime of the fact that
52 // we are running in a multithreaded environment.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053 InitCocoaMultiThreading();
54#endif
55}
56
57ThreadManager::~ThreadManager() {
kthelgasonde6adbe2017-02-22 00:42:11 -080058#if defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059 // This is called during exit, at which point apparently no NSAutoreleasePools
60 // are available; but we might still need them to do cleanup (or we get the
61 // "no autoreleasepool in place, just leaking" warning when exiting).
62 ScopedAutoreleasePool pool;
63#endif
kthelgasonde6adbe2017-02-22 00:42:11 -080064 UnwrapCurrentThread();
65 pthread_key_delete(key_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066}
67
68Thread *ThreadManager::CurrentThread() {
69 return static_cast<Thread *>(pthread_getspecific(key_));
70}
71
72void ThreadManager::SetCurrentThread(Thread *thread) {
73 pthread_setspecific(key_, thread);
74}
75#endif
76
77#if defined(WEBRTC_WIN)
78ThreadManager::ThreadManager() {
79 key_ = TlsAlloc();
80#ifndef NO_MAIN_THREAD_WRAPPING
81 WrapCurrentThread();
82#endif
83}
84
85ThreadManager::~ThreadManager() {
86 UnwrapCurrentThread();
87 TlsFree(key_);
88}
89
90Thread *ThreadManager::CurrentThread() {
91 return static_cast<Thread *>(TlsGetValue(key_));
92}
93
94void ThreadManager::SetCurrentThread(Thread *thread) {
95 TlsSetValue(key_, thread);
96}
97#endif
98
99Thread *ThreadManager::WrapCurrentThread() {
100 Thread* result = CurrentThread();
101 if (NULL == result) {
102 result = new Thread();
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000103 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104 }
105 return result;
106}
107
108void ThreadManager::UnwrapCurrentThread() {
109 Thread* t = CurrentThread();
110 if (t && !(t->IsOwned())) {
111 t->UnwrapCurrent();
112 delete t;
113 }
114}
115
116struct ThreadInit {
117 Thread* thread;
118 Runnable* runnable;
119};
120
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000121Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
122 : thread_(Thread::Current()),
123 previous_state_(thread_->SetAllowBlockingCalls(false)) {
124}
125
126Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800127 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000128 thread_->SetAllowBlockingCalls(previous_state_);
129}
130
danilchapbebf54c2016-04-28 01:32:48 -0700131Thread::Thread() : Thread(SocketServer::CreateDefault()) {}
132
133Thread::Thread(SocketServer* ss)
jbauch25d1f282016-02-05 00:25:02 -0800134 : MessageQueue(ss, false),
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000135 running_(true, false),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136#if defined(WEBRTC_WIN)
137 thread_(NULL),
138 thread_id_(0),
139#endif
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000140 owned_(true),
141 blocking_calls_allowed_(true) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142 SetName("Thread", this); // default name
danilchapbebf54c2016-04-28 01:32:48 -0700143 DoInit();
144}
145
146Thread::Thread(std::unique_ptr<SocketServer> ss)
147 : MessageQueue(std::move(ss), false),
148 running_(true, false),
149#if defined(WEBRTC_WIN)
150 thread_(NULL),
151 thread_id_(0),
152#endif
153 owned_(true),
154 blocking_calls_allowed_(true) {
155 SetName("Thread", this); // default name
156 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000157}
158
159Thread::~Thread() {
160 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800161 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000162}
163
danilchapbebf54c2016-04-28 01:32:48 -0700164std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
165 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
166}
167
168std::unique_ptr<Thread> Thread::Create() {
169 return std::unique_ptr<Thread>(
170 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
171}
172
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000174 AssertBlockingIsAllowedOnCurrentThread();
175
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000176#if defined(WEBRTC_WIN)
177 ::Sleep(milliseconds);
178 return true;
179#else
180 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
181 // so we use nanosleep() even though it has greater precision than necessary.
182 struct timespec ts;
183 ts.tv_sec = milliseconds / 1000;
184 ts.tv_nsec = (milliseconds % 1000) * 1000000;
185 int ret = nanosleep(&ts, NULL);
186 if (ret != 0) {
187 LOG_ERR(LS_WARNING) << "nanosleep() returning early";
188 return false;
189 }
190 return true;
191#endif
192}
193
194bool Thread::SetName(const std::string& name, const void* obj) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000195 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196 name_ = name;
197 if (obj) {
198 char buf[16];
199 sprintfn(buf, sizeof(buf), " 0x%p", obj);
200 name_ += buf;
201 }
202 return true;
203}
204
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205bool Thread::Start(Runnable* runnable) {
nisseede5da42017-01-12 05:15:36 -0800206 RTC_DCHECK(owned_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000207 if (!owned_) return false;
nisseede5da42017-01-12 05:15:36 -0800208 RTC_DCHECK(!running());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000209 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210
André Susano Pinto02a57972016-07-22 13:30:05 +0200211 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000212
213 // Make sure that ThreadManager is created on the main thread before
214 // we start a new thread.
215 ThreadManager::Instance();
216
217 ThreadInit* init = new ThreadInit;
218 init->thread = this;
219 init->runnable = runnable;
220#if defined(WEBRTC_WIN)
deadbeefdc20e262017-01-31 15:10:44 -0800221 thread_ = CreateThread(NULL, 0, PreRun, init, 0, &thread_id_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222 if (thread_) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000223 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000224 } else {
225 return false;
226 }
227#elif defined(WEBRTC_POSIX)
228 pthread_attr_t attr;
229 pthread_attr_init(&attr);
230
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000231 int error_code = pthread_create(&thread_, &attr, PreRun, init);
232 if (0 != error_code) {
233 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
234 return false;
235 }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000236 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237#endif
238 return true;
239}
240
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000241bool Thread::WrapCurrent() {
242 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
243}
244
245void Thread::UnwrapCurrent() {
246 // Clears the platform-specific thread-specific storage.
247 ThreadManager::Instance()->SetCurrentThread(NULL);
248#if defined(WEBRTC_WIN)
249 if (thread_ != NULL) {
250 if (!CloseHandle(thread_)) {
251 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
252 }
253 thread_ = NULL;
254 }
255#endif
256 running_.Reset();
257}
258
259void Thread::SafeWrapCurrent() {
260 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
261}
262
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263void Thread::Join() {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000264 if (running()) {
nisseede5da42017-01-12 05:15:36 -0800265 RTC_DCHECK(!IsCurrent());
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000266 if (Current() && !Current()->blocking_calls_allowed_) {
267 LOG(LS_WARNING) << "Waiting for the thread to join, "
268 << "but blocking calls have been disallowed";
269 }
270
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271#if defined(WEBRTC_WIN)
nisseede5da42017-01-12 05:15:36 -0800272 RTC_DCHECK(thread_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 WaitForSingleObject(thread_, INFINITE);
274 CloseHandle(thread_);
275 thread_ = NULL;
276 thread_id_ = 0;
277#elif defined(WEBRTC_POSIX)
278 void *pv;
279 pthread_join(thread_, &pv);
280#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000281 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282 }
283}
284
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000285bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800286 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000287 bool previous = blocking_calls_allowed_;
288 blocking_calls_allowed_ = allow;
289 return previous;
290}
291
292// static
293void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700294#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000295 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800296 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000297#endif
298}
299
deadbeefdc20e262017-01-31 15:10:44 -0800300// static
301#if defined(WEBRTC_WIN)
302DWORD WINAPI Thread::PreRun(LPVOID pv) {
303#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000304void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800305#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306 ThreadInit* init = static_cast<ThreadInit*>(pv);
307 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200308 rtc::SetCurrentThreadName(init->thread->name_.c_str());
kthelgasonde6adbe2017-02-22 00:42:11 -0800309#if defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310 // Make sure the new thread has an autoreleasepool
311 ScopedAutoreleasePool pool;
312#endif
kthelgasonde6adbe2017-02-22 00:42:11 -0800313 if (init->runnable) {
314 init->runnable->Run(init->thread);
315 } else {
316 init->thread->Run();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000317 }
kthelgasonde6adbe2017-02-22 00:42:11 -0800318 delete init;
319#ifdef WEBRTC_WIN
320 return 0;
321#else
322 return nullptr;
323#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324}
325
326void Thread::Run() {
327 ProcessMessages(kForever);
328}
329
330bool Thread::IsOwned() {
331 return owned_;
332}
333
334void Thread::Stop() {
335 MessageQueue::Quit();
336 Join();
337}
338
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700339void Thread::Send(const Location& posted_from,
340 MessageHandler* phandler,
341 uint32_t id,
342 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200343 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000344 return;
345
346 // Sent messages are sent to the MessageHandler directly, in the context
347 // of "thread", like Win32 SendMessage. If in the right context,
348 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000349 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700350 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351 msg.phandler = phandler;
352 msg.message_id = id;
353 msg.pdata = pdata;
354 if (IsCurrent()) {
355 phandler->OnMessage(&msg);
356 return;
357 }
358
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000359 AssertBlockingIsAllowedOnCurrentThread();
360
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361 AutoThread thread;
362 Thread *current_thread = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800363 RTC_DCHECK(current_thread != NULL); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000364
365 bool ready = false;
366 {
367 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000368 _SendMessage smsg;
369 smsg.thread = current_thread;
370 smsg.msg = msg;
371 smsg.ready = &ready;
372 sendlist_.push_back(smsg);
373 }
374
375 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800376 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000377
378 bool waited = false;
379 crit_.Enter();
380 while (!ready) {
381 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000382 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
383 // thread invoking calls on the current thread.
384 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000385 current_thread->socketserver()->Wait(kForever, false);
386 waited = true;
387 crit_.Enter();
388 }
389 crit_.Leave();
390
391 // Our Wait loop above may have consumed some WakeUp events for this
392 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
393 // cause problems for some SocketServers.
394 //
395 // Concrete example:
396 // Win32SocketServer on thread A calls Send on thread B. While processing the
397 // message, thread B Posts a message to A. We consume the wakeup for that
398 // Post while waiting for the Send to complete, which means that when we exit
399 // this loop, we need to issue another WakeUp, or else the Posted message
400 // won't be processed in a timely manner.
401
402 if (waited) {
403 current_thread->socketserver()->WakeUp();
404 }
405}
406
407void Thread::ReceiveSends() {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000408 ReceiveSendsFromThread(NULL);
409}
410
411void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 // Receive a sent message. Cleanup scenarios:
413 // - thread sending exits: We don't allow this, since thread can exit
414 // only via Join, so Send must complete.
415 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
416 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000417 _SendMessage smsg;
418
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000419 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000420 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000421 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000422
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000423 smsg.msg.phandler->OnMessage(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000424
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000425 crit_.Enter();
426 *smsg.ready = true;
427 smsg.thread->socketserver()->WakeUp();
428 }
429 crit_.Leave();
430}
431
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000432bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
433 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
434 it != sendlist_.end(); ++it) {
435 if (it->thread == source || source == NULL) {
436 *msg = *it;
437 sendlist_.erase(it);
438 return true;
439 }
440 }
441 return false;
442}
443
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700444void Thread::InvokeInternal(const Location& posted_from,
445 MessageHandler* handler) {
446 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
447 posted_from.file_and_line(), "src_func",
448 posted_from.function_name());
449 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000450}
451
Peter Boström0c4e06b2015-10-07 12:23:21 +0200452void Thread::Clear(MessageHandler* phandler,
453 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000454 MessageList* removed) {
455 CritScope cs(&crit_);
456
457 // Remove messages on sendlist_ with phandler
458 // Object target cleared: remove from send list, wakeup/set ready
459 // if sender not NULL.
460
461 std::list<_SendMessage>::iterator iter = sendlist_.begin();
462 while (iter != sendlist_.end()) {
463 _SendMessage smsg = *iter;
464 if (smsg.msg.Match(phandler, id)) {
465 if (removed) {
466 removed->push_back(smsg.msg);
467 } else {
468 delete smsg.msg.pdata;
469 }
470 iter = sendlist_.erase(iter);
471 *smsg.ready = true;
472 smsg.thread->socketserver()->WakeUp();
473 continue;
474 }
475 ++iter;
476 }
477
478 MessageQueue::Clear(phandler, id, removed);
479}
480
481bool Thread::ProcessMessages(int cmsLoop) {
Honghai Zhang82d78622016-05-06 11:29:15 -0700482 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000483 int cmsNext = cmsLoop;
484
485 while (true) {
kthelgasonde6adbe2017-02-22 00:42:11 -0800486#if defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000487 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
488 // Each thread is supposed to have an autorelease pool. Also for event loops
489 // like this, autorelease pool needs to be created and drained/released
490 // for each cycle.
491 ScopedAutoreleasePool pool;
492#endif
kthelgasonde6adbe2017-02-22 00:42:11 -0800493 Message msg;
494 if (!Get(&msg, cmsNext))
495 return !IsQuitting();
496 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000497
kthelgasonde6adbe2017-02-22 00:42:11 -0800498 if (cmsLoop != kForever) {
499 cmsNext = static_cast<int>(TimeUntil(msEnd));
500 if (cmsNext < 0)
501 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000502 }
503 }
504}
505
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000506bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
507 bool need_synchronize_access) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000508 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000509 return false;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000510
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000511#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000512 if (need_synchronize_access) {
513 // We explicitly ask for no rights other than synchronization.
514 // This gives us the best chance of succeeding.
515 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
516 if (!thread_) {
517 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
518 return false;
519 }
520 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000521 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000522#elif defined(WEBRTC_POSIX)
523 thread_ = pthread_self();
524#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000525
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000526 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000527 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000528 thread_manager->SetCurrentThread(this);
529 return true;
530}
531
danilchapbebf54c2016-04-28 01:32:48 -0700532AutoThread::AutoThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000533 if (!ThreadManager::Instance()->CurrentThread()) {
534 ThreadManager::Instance()->SetCurrentThread(this);
535 }
536}
537
538AutoThread::~AutoThread() {
539 Stop();
540 if (ThreadManager::Instance()->CurrentThread() == this) {
541 ThreadManager::Instance()->SetCurrentThread(NULL);
542 }
543}
544
545#if defined(WEBRTC_WIN)
aleloi8dd4ec32017-02-20 04:17:53 -0800546ComThread::~ComThread() {
547 Stop();
548}
549
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000550void ComThread::Run() {
551 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
nisseede5da42017-01-12 05:15:36 -0800552 RTC_DCHECK(SUCCEEDED(hr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000553 if (SUCCEEDED(hr)) {
554 Thread::Run();
555 CoUninitialize();
556 } else {
557 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
558 }
559}
560#endif
561
562} // namespace rtc