blob: ed0c44674183e5c141a7638953446a89ec07b65a [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
13#ifndef __has_feature
14#define __has_feature(x) 0 // Compatibility with non-clang or LLVM compilers.
15#endif // __has_feature
16
17#if defined(WEBRTC_WIN)
18#include <comdef.h>
19#elif defined(WEBRTC_POSIX)
20#include <time.h>
21#endif
22
nisseede5da42017-01-12 05:15:36 -080023#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024#include "webrtc/base/logging.h"
danilchapbebf54c2016-04-28 01:32:48 -070025#include "webrtc/base/nullsocketserver.h"
Tommiea14f0a2015-05-18 13:51:06 +020026#include "webrtc/base/platform_thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027#include "webrtc/base/stringutils.h"
28#include "webrtc/base/timeutils.h"
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070029#include "webrtc/base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030
31#if !__has_feature(objc_arc) && (defined(WEBRTC_MAC))
32#include "webrtc/base/maccocoathreadhelper.h"
33#include "webrtc/base/scoped_autorelease_pool.h"
34#endif
35
36namespace rtc {
37
38ThreadManager* ThreadManager::Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -070039 RTC_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040 return &thread_manager;
41}
42
43// static
44Thread* Thread::Current() {
45 return ThreadManager::Instance()->CurrentThread();
46}
47
48#if defined(WEBRTC_POSIX)
49ThreadManager::ThreadManager() {
50 pthread_key_create(&key_, NULL);
51#ifndef NO_MAIN_THREAD_WRAPPING
52 WrapCurrentThread();
53#endif
54#if !__has_feature(objc_arc) && (defined(WEBRTC_MAC))
55 // Under Automatic Reference Counting (ARC), you cannot use autorelease pools
56 // directly. Instead, you use @autoreleasepool blocks instead. Also, we are
57 // maintaining thread safety using immutability within context of GCD dispatch
58 // queues in this case.
59 InitCocoaMultiThreading();
60#endif
61}
62
63ThreadManager::~ThreadManager() {
64#if __has_feature(objc_arc)
65 @autoreleasepool
66#elif defined(WEBRTC_MAC)
67 // This is called during exit, at which point apparently no NSAutoreleasePools
68 // are available; but we might still need them to do cleanup (or we get the
69 // "no autoreleasepool in place, just leaking" warning when exiting).
70 ScopedAutoreleasePool pool;
71#endif
72 {
73 UnwrapCurrentThread();
74 pthread_key_delete(key_);
75 }
76}
77
78Thread *ThreadManager::CurrentThread() {
79 return static_cast<Thread *>(pthread_getspecific(key_));
80}
81
82void ThreadManager::SetCurrentThread(Thread *thread) {
83 pthread_setspecific(key_, thread);
84}
85#endif
86
87#if defined(WEBRTC_WIN)
88ThreadManager::ThreadManager() {
89 key_ = TlsAlloc();
90#ifndef NO_MAIN_THREAD_WRAPPING
91 WrapCurrentThread();
92#endif
93}
94
95ThreadManager::~ThreadManager() {
96 UnwrapCurrentThread();
97 TlsFree(key_);
98}
99
100Thread *ThreadManager::CurrentThread() {
101 return static_cast<Thread *>(TlsGetValue(key_));
102}
103
104void ThreadManager::SetCurrentThread(Thread *thread) {
105 TlsSetValue(key_, thread);
106}
107#endif
108
109Thread *ThreadManager::WrapCurrentThread() {
110 Thread* result = CurrentThread();
111 if (NULL == result) {
112 result = new Thread();
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000113 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000114 }
115 return result;
116}
117
118void ThreadManager::UnwrapCurrentThread() {
119 Thread* t = CurrentThread();
120 if (t && !(t->IsOwned())) {
121 t->UnwrapCurrent();
122 delete t;
123 }
124}
125
126struct ThreadInit {
127 Thread* thread;
128 Runnable* runnable;
129};
130
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000131Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
132 : thread_(Thread::Current()),
133 previous_state_(thread_->SetAllowBlockingCalls(false)) {
134}
135
136Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800137 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000138 thread_->SetAllowBlockingCalls(previous_state_);
139}
140
danilchapbebf54c2016-04-28 01:32:48 -0700141Thread::Thread() : Thread(SocketServer::CreateDefault()) {}
142
143Thread::Thread(SocketServer* ss)
jbauch25d1f282016-02-05 00:25:02 -0800144 : MessageQueue(ss, false),
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000145 running_(true, false),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146#if defined(WEBRTC_WIN)
147 thread_(NULL),
148 thread_id_(0),
149#endif
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000150 owned_(true),
151 blocking_calls_allowed_(true) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152 SetName("Thread", this); // default name
danilchapbebf54c2016-04-28 01:32:48 -0700153 DoInit();
154}
155
156Thread::Thread(std::unique_ptr<SocketServer> ss)
157 : MessageQueue(std::move(ss), false),
158 running_(true, false),
159#if defined(WEBRTC_WIN)
160 thread_(NULL),
161 thread_id_(0),
162#endif
163 owned_(true),
164 blocking_calls_allowed_(true) {
165 SetName("Thread", this); // default name
166 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167}
168
169Thread::~Thread() {
170 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800171 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172}
173
danilchapbebf54c2016-04-28 01:32:48 -0700174std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
175 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
176}
177
178std::unique_ptr<Thread> Thread::Create() {
179 return std::unique_ptr<Thread>(
180 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
181}
182
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000183bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000184 AssertBlockingIsAllowedOnCurrentThread();
185
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000186#if defined(WEBRTC_WIN)
187 ::Sleep(milliseconds);
188 return true;
189#else
190 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
191 // so we use nanosleep() even though it has greater precision than necessary.
192 struct timespec ts;
193 ts.tv_sec = milliseconds / 1000;
194 ts.tv_nsec = (milliseconds % 1000) * 1000000;
195 int ret = nanosleep(&ts, NULL);
196 if (ret != 0) {
197 LOG_ERR(LS_WARNING) << "nanosleep() returning early";
198 return false;
199 }
200 return true;
201#endif
202}
203
204bool Thread::SetName(const std::string& name, const void* obj) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000205 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000206 name_ = name;
207 if (obj) {
208 char buf[16];
209 sprintfn(buf, sizeof(buf), " 0x%p", obj);
210 name_ += buf;
211 }
212 return true;
213}
214
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215bool Thread::Start(Runnable* runnable) {
nisseede5da42017-01-12 05:15:36 -0800216 RTC_DCHECK(owned_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000217 if (!owned_) return false;
nisseede5da42017-01-12 05:15:36 -0800218 RTC_DCHECK(!running());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000219 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220
André Susano Pinto02a57972016-07-22 13:30:05 +0200221 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222
223 // Make sure that ThreadManager is created on the main thread before
224 // we start a new thread.
225 ThreadManager::Instance();
226
227 ThreadInit* init = new ThreadInit;
228 init->thread = this;
229 init->runnable = runnable;
230#if defined(WEBRTC_WIN)
deadbeefdc20e262017-01-31 15:10:44 -0800231 thread_ = CreateThread(NULL, 0, PreRun, init, 0, &thread_id_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232 if (thread_) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000233 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234 } else {
235 return false;
236 }
237#elif defined(WEBRTC_POSIX)
238 pthread_attr_t attr;
239 pthread_attr_init(&attr);
240
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000241 int error_code = pthread_create(&thread_, &attr, PreRun, init);
242 if (0 != error_code) {
243 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
244 return false;
245 }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000246 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247#endif
248 return true;
249}
250
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000251bool Thread::WrapCurrent() {
252 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
253}
254
255void Thread::UnwrapCurrent() {
256 // Clears the platform-specific thread-specific storage.
257 ThreadManager::Instance()->SetCurrentThread(NULL);
258#if defined(WEBRTC_WIN)
259 if (thread_ != NULL) {
260 if (!CloseHandle(thread_)) {
261 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
262 }
263 thread_ = NULL;
264 }
265#endif
266 running_.Reset();
267}
268
269void Thread::SafeWrapCurrent() {
270 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
271}
272
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273void Thread::Join() {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000274 if (running()) {
nisseede5da42017-01-12 05:15:36 -0800275 RTC_DCHECK(!IsCurrent());
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000276 if (Current() && !Current()->blocking_calls_allowed_) {
277 LOG(LS_WARNING) << "Waiting for the thread to join, "
278 << "but blocking calls have been disallowed";
279 }
280
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281#if defined(WEBRTC_WIN)
nisseede5da42017-01-12 05:15:36 -0800282 RTC_DCHECK(thread_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000283 WaitForSingleObject(thread_, INFINITE);
284 CloseHandle(thread_);
285 thread_ = NULL;
286 thread_id_ = 0;
287#elif defined(WEBRTC_POSIX)
288 void *pv;
289 pthread_join(thread_, &pv);
290#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000291 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292 }
293}
294
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000295bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800296 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000297 bool previous = blocking_calls_allowed_;
298 blocking_calls_allowed_ = allow;
299 return previous;
300}
301
302// static
303void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700304#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000305 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800306 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000307#endif
308}
309
deadbeefdc20e262017-01-31 15:10:44 -0800310// static
311#if defined(WEBRTC_WIN)
312DWORD WINAPI Thread::PreRun(LPVOID pv) {
313#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800315#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316 ThreadInit* init = static_cast<ThreadInit*>(pv);
317 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200318 rtc::SetCurrentThreadName(init->thread->name_.c_str());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000319#if __has_feature(objc_arc)
320 @autoreleasepool
321#elif defined(WEBRTC_MAC)
322 // Make sure the new thread has an autoreleasepool
323 ScopedAutoreleasePool pool;
324#endif
325 {
326 if (init->runnable) {
327 init->runnable->Run(init->thread);
328 } else {
329 init->thread->Run();
330 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000331 delete init;
deadbeefdc20e262017-01-31 15:10:44 -0800332#ifdef WEBRTC_WIN
333 return 0;
334#else
335 return nullptr;
336#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337 }
338}
339
340void Thread::Run() {
341 ProcessMessages(kForever);
342}
343
344bool Thread::IsOwned() {
345 return owned_;
346}
347
348void Thread::Stop() {
349 MessageQueue::Quit();
350 Join();
351}
352
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700353void Thread::Send(const Location& posted_from,
354 MessageHandler* phandler,
355 uint32_t id,
356 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200357 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000358 return;
359
360 // Sent messages are sent to the MessageHandler directly, in the context
361 // of "thread", like Win32 SendMessage. If in the right context,
362 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000363 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700364 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000365 msg.phandler = phandler;
366 msg.message_id = id;
367 msg.pdata = pdata;
368 if (IsCurrent()) {
369 phandler->OnMessage(&msg);
370 return;
371 }
372
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000373 AssertBlockingIsAllowedOnCurrentThread();
374
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375 AutoThread thread;
376 Thread *current_thread = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800377 RTC_DCHECK(current_thread != NULL); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000378
379 bool ready = false;
380 {
381 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000382 _SendMessage smsg;
383 smsg.thread = current_thread;
384 smsg.msg = msg;
385 smsg.ready = &ready;
386 sendlist_.push_back(smsg);
387 }
388
389 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800390 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000391
392 bool waited = false;
393 crit_.Enter();
394 while (!ready) {
395 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000396 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
397 // thread invoking calls on the current thread.
398 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000399 current_thread->socketserver()->Wait(kForever, false);
400 waited = true;
401 crit_.Enter();
402 }
403 crit_.Leave();
404
405 // Our Wait loop above may have consumed some WakeUp events for this
406 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
407 // cause problems for some SocketServers.
408 //
409 // Concrete example:
410 // Win32SocketServer on thread A calls Send on thread B. While processing the
411 // message, thread B Posts a message to A. We consume the wakeup for that
412 // Post while waiting for the Send to complete, which means that when we exit
413 // this loop, we need to issue another WakeUp, or else the Posted message
414 // won't be processed in a timely manner.
415
416 if (waited) {
417 current_thread->socketserver()->WakeUp();
418 }
419}
420
421void Thread::ReceiveSends() {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000422 ReceiveSendsFromThread(NULL);
423}
424
425void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000426 // Receive a sent message. Cleanup scenarios:
427 // - thread sending exits: We don't allow this, since thread can exit
428 // only via Join, so Send must complete.
429 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
430 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000431 _SendMessage smsg;
432
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000433 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000434 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000435 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000436
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000437 smsg.msg.phandler->OnMessage(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000438
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000439 crit_.Enter();
440 *smsg.ready = true;
441 smsg.thread->socketserver()->WakeUp();
442 }
443 crit_.Leave();
444}
445
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000446bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
447 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
448 it != sendlist_.end(); ++it) {
449 if (it->thread == source || source == NULL) {
450 *msg = *it;
451 sendlist_.erase(it);
452 return true;
453 }
454 }
455 return false;
456}
457
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700458void Thread::InvokeInternal(const Location& posted_from,
459 MessageHandler* handler) {
460 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
461 posted_from.file_and_line(), "src_func",
462 posted_from.function_name());
463 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000464}
465
Peter Boström0c4e06b2015-10-07 12:23:21 +0200466void Thread::Clear(MessageHandler* phandler,
467 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000468 MessageList* removed) {
469 CritScope cs(&crit_);
470
471 // Remove messages on sendlist_ with phandler
472 // Object target cleared: remove from send list, wakeup/set ready
473 // if sender not NULL.
474
475 std::list<_SendMessage>::iterator iter = sendlist_.begin();
476 while (iter != sendlist_.end()) {
477 _SendMessage smsg = *iter;
478 if (smsg.msg.Match(phandler, id)) {
479 if (removed) {
480 removed->push_back(smsg.msg);
481 } else {
482 delete smsg.msg.pdata;
483 }
484 iter = sendlist_.erase(iter);
485 *smsg.ready = true;
486 smsg.thread->socketserver()->WakeUp();
487 continue;
488 }
489 ++iter;
490 }
491
492 MessageQueue::Clear(phandler, id, removed);
493}
494
495bool Thread::ProcessMessages(int cmsLoop) {
Honghai Zhang82d78622016-05-06 11:29:15 -0700496 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000497 int cmsNext = cmsLoop;
498
499 while (true) {
500#if __has_feature(objc_arc)
501 @autoreleasepool
502#elif defined(WEBRTC_MAC)
503 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
504 // Each thread is supposed to have an autorelease pool. Also for event loops
505 // like this, autorelease pool needs to be created and drained/released
506 // for each cycle.
507 ScopedAutoreleasePool pool;
508#endif
509 {
510 Message msg;
511 if (!Get(&msg, cmsNext))
512 return !IsQuitting();
513 Dispatch(&msg);
514
515 if (cmsLoop != kForever) {
Taylor Brandstetter2b3bf6b2016-05-19 14:57:31 -0700516 cmsNext = static_cast<int>(TimeUntil(msEnd));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000517 if (cmsNext < 0)
518 return true;
519 }
520 }
521 }
522}
523
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000524bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
525 bool need_synchronize_access) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000526 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000527 return false;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000528
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000529#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000530 if (need_synchronize_access) {
531 // We explicitly ask for no rights other than synchronization.
532 // This gives us the best chance of succeeding.
533 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
534 if (!thread_) {
535 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
536 return false;
537 }
538 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000539 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000540#elif defined(WEBRTC_POSIX)
541 thread_ = pthread_self();
542#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000543
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000544 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000545 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000546 thread_manager->SetCurrentThread(this);
547 return true;
548}
549
danilchapbebf54c2016-04-28 01:32:48 -0700550AutoThread::AutoThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000551 if (!ThreadManager::Instance()->CurrentThread()) {
552 ThreadManager::Instance()->SetCurrentThread(this);
553 }
554}
555
556AutoThread::~AutoThread() {
557 Stop();
558 if (ThreadManager::Instance()->CurrentThread() == this) {
559 ThreadManager::Instance()->SetCurrentThread(NULL);
560 }
561}
562
563#if defined(WEBRTC_WIN)
564void ComThread::Run() {
565 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
nisseede5da42017-01-12 05:15:36 -0800566 RTC_DCHECK(SUCCEEDED(hr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000567 if (SUCCEEDED(hr)) {
568 Thread::Run();
569 CoUninitialize();
570 } else {
571 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
572 }
573}
574#endif
575
576} // namespace rtc