blob: 6aded99f1f1f21438c0e6c1ca50af3216ec2f2da [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
23#include "webrtc/base/common.h"
24#include "webrtc/base/logging.h"
25#include "webrtc/base/stringutils.h"
26#include "webrtc/base/timeutils.h"
27
28#if !__has_feature(objc_arc) && (defined(WEBRTC_MAC))
29#include "webrtc/base/maccocoathreadhelper.h"
30#include "webrtc/base/scoped_autorelease_pool.h"
31#endif
32
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000033#include "webrtc/base/trace_event.h"
34
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035namespace rtc {
36
37ThreadManager* ThreadManager::Instance() {
38 LIBJINGLE_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
39 return &thread_manager;
40}
41
42// static
43Thread* Thread::Current() {
44 return ThreadManager::Instance()->CurrentThread();
45}
46
47#if defined(WEBRTC_POSIX)
48ThreadManager::ThreadManager() {
49 pthread_key_create(&key_, NULL);
50#ifndef NO_MAIN_THREAD_WRAPPING
51 WrapCurrentThread();
52#endif
53#if !__has_feature(objc_arc) && (defined(WEBRTC_MAC))
54 // Under Automatic Reference Counting (ARC), you cannot use autorelease pools
55 // directly. Instead, you use @autoreleasepool blocks instead. Also, we are
56 // maintaining thread safety using immutability within context of GCD dispatch
57 // queues in this case.
58 InitCocoaMultiThreading();
59#endif
60}
61
62ThreadManager::~ThreadManager() {
63#if __has_feature(objc_arc)
64 @autoreleasepool
65#elif defined(WEBRTC_MAC)
66 // This is called during exit, at which point apparently no NSAutoreleasePools
67 // are available; but we might still need them to do cleanup (or we get the
68 // "no autoreleasepool in place, just leaking" warning when exiting).
69 ScopedAutoreleasePool pool;
70#endif
71 {
72 UnwrapCurrentThread();
73 pthread_key_delete(key_);
74 }
75}
76
77Thread *ThreadManager::CurrentThread() {
78 return static_cast<Thread *>(pthread_getspecific(key_));
79}
80
81void ThreadManager::SetCurrentThread(Thread *thread) {
82 pthread_setspecific(key_, thread);
83}
84#endif
85
86#if defined(WEBRTC_WIN)
87ThreadManager::ThreadManager() {
88 key_ = TlsAlloc();
89#ifndef NO_MAIN_THREAD_WRAPPING
90 WrapCurrentThread();
91#endif
92}
93
94ThreadManager::~ThreadManager() {
95 UnwrapCurrentThread();
96 TlsFree(key_);
97}
98
99Thread *ThreadManager::CurrentThread() {
100 return static_cast<Thread *>(TlsGetValue(key_));
101}
102
103void ThreadManager::SetCurrentThread(Thread *thread) {
104 TlsSetValue(key_, thread);
105}
106#endif
107
108Thread *ThreadManager::WrapCurrentThread() {
109 Thread* result = CurrentThread();
110 if (NULL == result) {
111 result = new Thread();
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000112 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000113 }
114 return result;
115}
116
117void ThreadManager::UnwrapCurrentThread() {
118 Thread* t = CurrentThread();
119 if (t && !(t->IsOwned())) {
120 t->UnwrapCurrent();
121 delete t;
122 }
123}
124
125struct ThreadInit {
126 Thread* thread;
127 Runnable* runnable;
128};
129
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000130Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
131 : thread_(Thread::Current()),
132 previous_state_(thread_->SetAllowBlockingCalls(false)) {
133}
134
135Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
136 ASSERT(thread_->IsCurrent());
137 thread_->SetAllowBlockingCalls(previous_state_);
138}
139
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140Thread::Thread(SocketServer* ss)
141 : MessageQueue(ss),
142 priority_(PRIORITY_NORMAL),
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000143 running_(true, false),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144#if defined(WEBRTC_WIN)
145 thread_(NULL),
146 thread_id_(0),
147#endif
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000148 owned_(true),
149 blocking_calls_allowed_(true) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000150 SetName("Thread", this); // default name
151}
152
153Thread::~Thread() {
154 Stop();
henrike@webrtc.org99b41622014-05-21 20:42:17 +0000155 Clear(NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000156}
157
158bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000159 AssertBlockingIsAllowedOnCurrentThread();
160
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000161#if defined(WEBRTC_WIN)
162 ::Sleep(milliseconds);
163 return true;
164#else
165 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
166 // so we use nanosleep() even though it has greater precision than necessary.
167 struct timespec ts;
168 ts.tv_sec = milliseconds / 1000;
169 ts.tv_nsec = (milliseconds % 1000) * 1000000;
170 int ret = nanosleep(&ts, NULL);
171 if (ret != 0) {
172 LOG_ERR(LS_WARNING) << "nanosleep() returning early";
173 return false;
174 }
175 return true;
176#endif
177}
178
179bool Thread::SetName(const std::string& name, const void* obj) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000180 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000181 name_ = name;
182 if (obj) {
183 char buf[16];
184 sprintfn(buf, sizeof(buf), " 0x%p", obj);
185 name_ += buf;
186 }
187 return true;
188}
189
190bool Thread::SetPriority(ThreadPriority priority) {
191#if defined(WEBRTC_WIN)
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000192 if (running()) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000193 ASSERT(thread_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000194 BOOL ret = FALSE;
195 if (priority == PRIORITY_NORMAL) {
196 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_NORMAL);
197 } else if (priority == PRIORITY_HIGH) {
198 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_HIGHEST);
199 } else if (priority == PRIORITY_ABOVE_NORMAL) {
200 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL);
201 } else if (priority == PRIORITY_IDLE) {
202 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_IDLE);
203 }
204 if (!ret) {
205 return false;
206 }
207 }
208 priority_ = priority;
209 return true;
210#else
211 // TODO: Implement for Linux/Mac if possible.
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000212 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213 priority_ = priority;
214 return true;
215#endif
216}
217
218bool Thread::Start(Runnable* runnable) {
219 ASSERT(owned_);
220 if (!owned_) return false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000221 ASSERT(!running());
222 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223
224 Restart(); // reset fStop_ if the thread is being restarted
225
226 // Make sure that ThreadManager is created on the main thread before
227 // we start a new thread.
228 ThreadManager::Instance();
229
230 ThreadInit* init = new ThreadInit;
231 init->thread = this;
232 init->runnable = runnable;
233#if defined(WEBRTC_WIN)
234 DWORD flags = 0;
235 if (priority_ != PRIORITY_NORMAL) {
236 flags = CREATE_SUSPENDED;
237 }
238 thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PreRun, init, flags,
239 &thread_id_);
240 if (thread_) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000241 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242 if (priority_ != PRIORITY_NORMAL) {
243 SetPriority(priority_);
244 ::ResumeThread(thread_);
245 }
246 } else {
247 return false;
248 }
249#elif defined(WEBRTC_POSIX)
250 pthread_attr_t attr;
251 pthread_attr_init(&attr);
252
253 // Thread priorities are not supported in NaCl.
254#if !defined(__native_client__)
255 if (priority_ != PRIORITY_NORMAL) {
256 if (priority_ == PRIORITY_IDLE) {
257 // There is no POSIX-standard way to set a below-normal priority for an
258 // individual thread (only whole process), so let's not support it.
259 LOG(LS_WARNING) << "PRIORITY_IDLE not supported";
260 } else {
261 // Set real-time round-robin policy.
262 if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0) {
263 LOG(LS_ERROR) << "pthread_attr_setschedpolicy";
264 }
265 struct sched_param param;
266 if (pthread_attr_getschedparam(&attr, &param) != 0) {
267 LOG(LS_ERROR) << "pthread_attr_getschedparam";
268 } else {
269 // The numbers here are arbitrary.
270 if (priority_ == PRIORITY_HIGH) {
271 param.sched_priority = 6; // 6 = HIGH
272 } else {
273 ASSERT(priority_ == PRIORITY_ABOVE_NORMAL);
274 param.sched_priority = 4; // 4 = ABOVE_NORMAL
275 }
276 if (pthread_attr_setschedparam(&attr, &param) != 0) {
277 LOG(LS_ERROR) << "pthread_attr_setschedparam";
278 }
279 }
280 }
281 }
282#endif // !defined(__native_client__)
283
284 int error_code = pthread_create(&thread_, &attr, PreRun, init);
285 if (0 != error_code) {
286 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
287 return false;
288 }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000289 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290#endif
291 return true;
292}
293
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000294bool Thread::WrapCurrent() {
295 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
296}
297
298void Thread::UnwrapCurrent() {
299 // Clears the platform-specific thread-specific storage.
300 ThreadManager::Instance()->SetCurrentThread(NULL);
301#if defined(WEBRTC_WIN)
302 if (thread_ != NULL) {
303 if (!CloseHandle(thread_)) {
304 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
305 }
306 thread_ = NULL;
307 }
308#endif
309 running_.Reset();
310}
311
312void Thread::SafeWrapCurrent() {
313 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
314}
315
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316void Thread::Join() {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000317 if (running()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000318 ASSERT(!IsCurrent());
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000319 if (Current() && !Current()->blocking_calls_allowed_) {
320 LOG(LS_WARNING) << "Waiting for the thread to join, "
321 << "but blocking calls have been disallowed";
322 }
323
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000325 ASSERT(thread_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326 WaitForSingleObject(thread_, INFINITE);
327 CloseHandle(thread_);
328 thread_ = NULL;
329 thread_id_ = 0;
330#elif defined(WEBRTC_POSIX)
331 void *pv;
332 pthread_join(thread_, &pv);
333#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000334 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335 }
336}
337
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000338bool Thread::SetAllowBlockingCalls(bool allow) {
339 ASSERT(IsCurrent());
340 bool previous = blocking_calls_allowed_;
341 blocking_calls_allowed_ = allow;
342 return previous;
343}
344
345// static
346void Thread::AssertBlockingIsAllowedOnCurrentThread() {
347#ifdef _DEBUG
348 Thread* current = Thread::Current();
349 ASSERT(!current || current->blocking_calls_allowed_);
350#endif
351}
352
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000353#if defined(WEBRTC_WIN)
354// As seen on MSDN.
355// http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx
356#define MSDEV_SET_THREAD_NAME 0x406D1388
357typedef struct tagTHREADNAME_INFO {
358 DWORD dwType;
359 LPCSTR szName;
360 DWORD dwThreadID;
361 DWORD dwFlags;
362} THREADNAME_INFO;
363
364void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) {
365 THREADNAME_INFO info;
366 info.dwType = 0x1000;
367 info.szName = szThreadName;
368 info.dwThreadID = dwThreadID;
369 info.dwFlags = 0;
370
371 __try {
372 RaiseException(MSDEV_SET_THREAD_NAME, 0, sizeof(info) / sizeof(DWORD),
373 reinterpret_cast<ULONG_PTR*>(&info));
374 }
375 __except(EXCEPTION_CONTINUE_EXECUTION) {
376 }
377}
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000378#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000379
380void* Thread::PreRun(void* pv) {
381 ThreadInit* init = static_cast<ThreadInit*>(pv);
382 ThreadManager::Instance()->SetCurrentThread(init->thread);
383#if defined(WEBRTC_WIN)
384 SetThreadName(GetCurrentThreadId(), init->thread->name_.c_str());
385#elif defined(WEBRTC_POSIX)
386 // TODO: See if naming exists for pthreads.
387#endif
388#if __has_feature(objc_arc)
389 @autoreleasepool
390#elif defined(WEBRTC_MAC)
391 // Make sure the new thread has an autoreleasepool
392 ScopedAutoreleasePool pool;
393#endif
394 {
395 if (init->runnable) {
396 init->runnable->Run(init->thread);
397 } else {
398 init->thread->Run();
399 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000400 delete init;
401 return NULL;
402 }
403}
404
405void Thread::Run() {
406 ProcessMessages(kForever);
407}
408
409bool Thread::IsOwned() {
410 return owned_;
411}
412
413void Thread::Stop() {
414 MessageQueue::Quit();
415 Join();
416}
417
418void Thread::Send(MessageHandler *phandler, uint32 id, MessageData *pdata) {
419 if (fStop_)
420 return;
421
422 // Sent messages are sent to the MessageHandler directly, in the context
423 // of "thread", like Win32 SendMessage. If in the right context,
424 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000425 Message msg;
426 msg.phandler = phandler;
427 msg.message_id = id;
428 msg.pdata = pdata;
429 if (IsCurrent()) {
430 phandler->OnMessage(&msg);
431 return;
432 }
433
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000434 AssertBlockingIsAllowedOnCurrentThread();
435
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000436 AutoThread thread;
437 Thread *current_thread = Thread::Current();
438 ASSERT(current_thread != NULL); // AutoThread ensures this
439
440 bool ready = false;
441 {
442 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000443 _SendMessage smsg;
444 smsg.thread = current_thread;
445 smsg.msg = msg;
446 smsg.ready = &ready;
447 sendlist_.push_back(smsg);
448 }
449
450 // Wait for a reply
451
452 ss_->WakeUp();
453
454 bool waited = false;
455 crit_.Enter();
456 while (!ready) {
457 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000458 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
459 // thread invoking calls on the current thread.
460 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000461 current_thread->socketserver()->Wait(kForever, false);
462 waited = true;
463 crit_.Enter();
464 }
465 crit_.Leave();
466
467 // Our Wait loop above may have consumed some WakeUp events for this
468 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
469 // cause problems for some SocketServers.
470 //
471 // Concrete example:
472 // Win32SocketServer on thread A calls Send on thread B. While processing the
473 // message, thread B Posts a message to A. We consume the wakeup for that
474 // Post while waiting for the Send to complete, which means that when we exit
475 // this loop, we need to issue another WakeUp, or else the Posted message
476 // won't be processed in a timely manner.
477
478 if (waited) {
479 current_thread->socketserver()->WakeUp();
480 }
481}
482
483void Thread::ReceiveSends() {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000484 ReceiveSendsFromThread(NULL);
485}
486
487void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000488 // Receive a sent message. Cleanup scenarios:
489 // - thread sending exits: We don't allow this, since thread can exit
490 // only via Join, so Send must complete.
491 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
492 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000493 _SendMessage smsg;
494
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000495 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000496 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000497 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000498
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000499 smsg.msg.phandler->OnMessage(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000500
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000501 crit_.Enter();
502 *smsg.ready = true;
503 smsg.thread->socketserver()->WakeUp();
504 }
505 crit_.Leave();
506}
507
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000508bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
509 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
510 it != sendlist_.end(); ++it) {
511 if (it->thread == source || source == NULL) {
512 *msg = *it;
513 sendlist_.erase(it);
514 return true;
515 }
516 }
517 return false;
518}
519
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000520void Thread::InvokeBegin() {
521 TRACE_EVENT_BEGIN0("webrtc", "Thread::Invoke");
522}
523
524void Thread::InvokeEnd() {
525 TRACE_EVENT_END0("webrtc", "Thread::Invoke");
526}
527
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000528void Thread::Clear(MessageHandler *phandler, uint32 id,
529 MessageList* removed) {
530 CritScope cs(&crit_);
531
532 // Remove messages on sendlist_ with phandler
533 // Object target cleared: remove from send list, wakeup/set ready
534 // if sender not NULL.
535
536 std::list<_SendMessage>::iterator iter = sendlist_.begin();
537 while (iter != sendlist_.end()) {
538 _SendMessage smsg = *iter;
539 if (smsg.msg.Match(phandler, id)) {
540 if (removed) {
541 removed->push_back(smsg.msg);
542 } else {
543 delete smsg.msg.pdata;
544 }
545 iter = sendlist_.erase(iter);
546 *smsg.ready = true;
547 smsg.thread->socketserver()->WakeUp();
548 continue;
549 }
550 ++iter;
551 }
552
553 MessageQueue::Clear(phandler, id, removed);
554}
555
556bool Thread::ProcessMessages(int cmsLoop) {
557 uint32 msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
558 int cmsNext = cmsLoop;
559
560 while (true) {
561#if __has_feature(objc_arc)
562 @autoreleasepool
563#elif defined(WEBRTC_MAC)
564 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
565 // Each thread is supposed to have an autorelease pool. Also for event loops
566 // like this, autorelease pool needs to be created and drained/released
567 // for each cycle.
568 ScopedAutoreleasePool pool;
569#endif
570 {
571 Message msg;
572 if (!Get(&msg, cmsNext))
573 return !IsQuitting();
574 Dispatch(&msg);
575
576 if (cmsLoop != kForever) {
577 cmsNext = TimeUntil(msEnd);
578 if (cmsNext < 0)
579 return true;
580 }
581 }
582 }
583}
584
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000585bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
586 bool need_synchronize_access) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000587 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000588 return false;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000589
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000590#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000591 if (need_synchronize_access) {
592 // We explicitly ask for no rights other than synchronization.
593 // This gives us the best chance of succeeding.
594 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
595 if (!thread_) {
596 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
597 return false;
598 }
599 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000600 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000601#elif defined(WEBRTC_POSIX)
602 thread_ = pthread_self();
603#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000604
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000605 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000606 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000607 thread_manager->SetCurrentThread(this);
608 return true;
609}
610
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000611AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
612 if (!ThreadManager::Instance()->CurrentThread()) {
613 ThreadManager::Instance()->SetCurrentThread(this);
614 }
615}
616
617AutoThread::~AutoThread() {
618 Stop();
619 if (ThreadManager::Instance()->CurrentThread() == this) {
620 ThreadManager::Instance()->SetCurrentThread(NULL);
621 }
622}
623
624#if defined(WEBRTC_WIN)
625void ComThread::Run() {
626 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
627 ASSERT(SUCCEEDED(hr));
628 if (SUCCEEDED(hr)) {
629 Thread::Run();
630 CoUninitialize();
631 } else {
632 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
633 }
634}
635#endif
636
637} // namespace rtc