blob: 6da9a7fbbd721974c1b2d2cb33087054562d559c [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
33namespace rtc {
34
35ThreadManager* ThreadManager::Instance() {
36 LIBJINGLE_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
37 return &thread_manager;
38}
39
40// static
41Thread* Thread::Current() {
42 return ThreadManager::Instance()->CurrentThread();
43}
44
45#if defined(WEBRTC_POSIX)
46ThreadManager::ThreadManager() {
47 pthread_key_create(&key_, NULL);
48#ifndef NO_MAIN_THREAD_WRAPPING
49 WrapCurrentThread();
50#endif
51#if !__has_feature(objc_arc) && (defined(WEBRTC_MAC))
52 // Under Automatic Reference Counting (ARC), you cannot use autorelease pools
53 // directly. Instead, you use @autoreleasepool blocks instead. Also, we are
54 // maintaining thread safety using immutability within context of GCD dispatch
55 // queues in this case.
56 InitCocoaMultiThreading();
57#endif
58}
59
60ThreadManager::~ThreadManager() {
61#if __has_feature(objc_arc)
62 @autoreleasepool
63#elif defined(WEBRTC_MAC)
64 // This is called during exit, at which point apparently no NSAutoreleasePools
65 // are available; but we might still need them to do cleanup (or we get the
66 // "no autoreleasepool in place, just leaking" warning when exiting).
67 ScopedAutoreleasePool pool;
68#endif
69 {
70 UnwrapCurrentThread();
71 pthread_key_delete(key_);
72 }
73}
74
75Thread *ThreadManager::CurrentThread() {
76 return static_cast<Thread *>(pthread_getspecific(key_));
77}
78
79void ThreadManager::SetCurrentThread(Thread *thread) {
80 pthread_setspecific(key_, thread);
81}
82#endif
83
84#if defined(WEBRTC_WIN)
85ThreadManager::ThreadManager() {
86 key_ = TlsAlloc();
87#ifndef NO_MAIN_THREAD_WRAPPING
88 WrapCurrentThread();
89#endif
90}
91
92ThreadManager::~ThreadManager() {
93 UnwrapCurrentThread();
94 TlsFree(key_);
95}
96
97Thread *ThreadManager::CurrentThread() {
98 return static_cast<Thread *>(TlsGetValue(key_));
99}
100
101void ThreadManager::SetCurrentThread(Thread *thread) {
102 TlsSetValue(key_, thread);
103}
104#endif
105
106Thread *ThreadManager::WrapCurrentThread() {
107 Thread* result = CurrentThread();
108 if (NULL == result) {
109 result = new Thread();
110 result->WrapCurrentWithThreadManager(this);
111 }
112 return result;
113}
114
115void ThreadManager::UnwrapCurrentThread() {
116 Thread* t = CurrentThread();
117 if (t && !(t->IsOwned())) {
118 t->UnwrapCurrent();
119 delete t;
120 }
121}
122
123struct ThreadInit {
124 Thread* thread;
125 Runnable* runnable;
126};
127
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000128Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
129 : thread_(Thread::Current()),
130 previous_state_(thread_->SetAllowBlockingCalls(false)) {
131}
132
133Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
134 ASSERT(thread_->IsCurrent());
135 thread_->SetAllowBlockingCalls(previous_state_);
136}
137
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138Thread::Thread(SocketServer* ss)
139 : MessageQueue(ss),
140 priority_(PRIORITY_NORMAL),
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000141 running_(true, false),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142#if defined(WEBRTC_WIN)
143 thread_(NULL),
144 thread_id_(0),
145#endif
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000146 owned_(true),
147 blocking_calls_allowed_(true) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000148 SetName("Thread", this); // default name
149}
150
151Thread::~Thread() {
152 Stop();
henrike@webrtc.org99b41622014-05-21 20:42:17 +0000153 Clear(NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000154}
155
156bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000157 AssertBlockingIsAllowedOnCurrentThread();
158
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000159#if defined(WEBRTC_WIN)
160 ::Sleep(milliseconds);
161 return true;
162#else
163 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
164 // so we use nanosleep() even though it has greater precision than necessary.
165 struct timespec ts;
166 ts.tv_sec = milliseconds / 1000;
167 ts.tv_nsec = (milliseconds % 1000) * 1000000;
168 int ret = nanosleep(&ts, NULL);
169 if (ret != 0) {
170 LOG_ERR(LS_WARNING) << "nanosleep() returning early";
171 return false;
172 }
173 return true;
174#endif
175}
176
177bool Thread::SetName(const std::string& name, const void* obj) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000178 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179 name_ = name;
180 if (obj) {
181 char buf[16];
182 sprintfn(buf, sizeof(buf), " 0x%p", obj);
183 name_ += buf;
184 }
185 return true;
186}
187
188bool Thread::SetPriority(ThreadPriority priority) {
189#if defined(WEBRTC_WIN)
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000190 if (running()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000191 BOOL ret = FALSE;
192 if (priority == PRIORITY_NORMAL) {
193 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_NORMAL);
194 } else if (priority == PRIORITY_HIGH) {
195 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_HIGHEST);
196 } else if (priority == PRIORITY_ABOVE_NORMAL) {
197 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL);
198 } else if (priority == PRIORITY_IDLE) {
199 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_IDLE);
200 }
201 if (!ret) {
202 return false;
203 }
204 }
205 priority_ = priority;
206 return true;
207#else
208 // TODO: Implement for Linux/Mac if possible.
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000209 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210 priority_ = priority;
211 return true;
212#endif
213}
214
215bool Thread::Start(Runnable* runnable) {
216 ASSERT(owned_);
217 if (!owned_) return false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000218 ASSERT(!running());
219 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220
221 Restart(); // reset fStop_ if the thread is being restarted
222
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)
231 DWORD flags = 0;
232 if (priority_ != PRIORITY_NORMAL) {
233 flags = CREATE_SUSPENDED;
234 }
235 thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PreRun, init, flags,
236 &thread_id_);
237 if (thread_) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000238 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000239 if (priority_ != PRIORITY_NORMAL) {
240 SetPriority(priority_);
241 ::ResumeThread(thread_);
242 }
243 } else {
244 return false;
245 }
246#elif defined(WEBRTC_POSIX)
247 pthread_attr_t attr;
248 pthread_attr_init(&attr);
249
250 // Thread priorities are not supported in NaCl.
251#if !defined(__native_client__)
252 if (priority_ != PRIORITY_NORMAL) {
253 if (priority_ == PRIORITY_IDLE) {
254 // There is no POSIX-standard way to set a below-normal priority for an
255 // individual thread (only whole process), so let's not support it.
256 LOG(LS_WARNING) << "PRIORITY_IDLE not supported";
257 } else {
258 // Set real-time round-robin policy.
259 if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0) {
260 LOG(LS_ERROR) << "pthread_attr_setschedpolicy";
261 }
262 struct sched_param param;
263 if (pthread_attr_getschedparam(&attr, &param) != 0) {
264 LOG(LS_ERROR) << "pthread_attr_getschedparam";
265 } else {
266 // The numbers here are arbitrary.
267 if (priority_ == PRIORITY_HIGH) {
268 param.sched_priority = 6; // 6 = HIGH
269 } else {
270 ASSERT(priority_ == PRIORITY_ABOVE_NORMAL);
271 param.sched_priority = 4; // 4 = ABOVE_NORMAL
272 }
273 if (pthread_attr_setschedparam(&attr, &param) != 0) {
274 LOG(LS_ERROR) << "pthread_attr_setschedparam";
275 }
276 }
277 }
278 }
279#endif // !defined(__native_client__)
280
281 int error_code = pthread_create(&thread_, &attr, PreRun, init);
282 if (0 != error_code) {
283 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
284 return false;
285 }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000286 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287#endif
288 return true;
289}
290
291void Thread::Join() {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000292 AssertBlockingIsAllowedOnCurrentThread();
293
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000294 if (running()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295 ASSERT(!IsCurrent());
296#if defined(WEBRTC_WIN)
297 WaitForSingleObject(thread_, INFINITE);
298 CloseHandle(thread_);
299 thread_ = NULL;
300 thread_id_ = 0;
301#elif defined(WEBRTC_POSIX)
302 void *pv;
303 pthread_join(thread_, &pv);
304#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000305 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306 }
307}
308
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000309bool Thread::SetAllowBlockingCalls(bool allow) {
310 ASSERT(IsCurrent());
311 bool previous = blocking_calls_allowed_;
312 blocking_calls_allowed_ = allow;
313 return previous;
314}
315
316// static
317void Thread::AssertBlockingIsAllowedOnCurrentThread() {
318#ifdef _DEBUG
319 Thread* current = Thread::Current();
320 ASSERT(!current || current->blocking_calls_allowed_);
321#endif
322}
323
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324#if defined(WEBRTC_WIN)
325// As seen on MSDN.
326// http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx
327#define MSDEV_SET_THREAD_NAME 0x406D1388
328typedef struct tagTHREADNAME_INFO {
329 DWORD dwType;
330 LPCSTR szName;
331 DWORD dwThreadID;
332 DWORD dwFlags;
333} THREADNAME_INFO;
334
335void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) {
336 THREADNAME_INFO info;
337 info.dwType = 0x1000;
338 info.szName = szThreadName;
339 info.dwThreadID = dwThreadID;
340 info.dwFlags = 0;
341
342 __try {
343 RaiseException(MSDEV_SET_THREAD_NAME, 0, sizeof(info) / sizeof(DWORD),
344 reinterpret_cast<ULONG_PTR*>(&info));
345 }
346 __except(EXCEPTION_CONTINUE_EXECUTION) {
347 }
348}
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000349#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350
351void* Thread::PreRun(void* pv) {
352 ThreadInit* init = static_cast<ThreadInit*>(pv);
353 ThreadManager::Instance()->SetCurrentThread(init->thread);
354#if defined(WEBRTC_WIN)
355 SetThreadName(GetCurrentThreadId(), init->thread->name_.c_str());
356#elif defined(WEBRTC_POSIX)
357 // TODO: See if naming exists for pthreads.
358#endif
359#if __has_feature(objc_arc)
360 @autoreleasepool
361#elif defined(WEBRTC_MAC)
362 // Make sure the new thread has an autoreleasepool
363 ScopedAutoreleasePool pool;
364#endif
365 {
366 if (init->runnable) {
367 init->runnable->Run(init->thread);
368 } else {
369 init->thread->Run();
370 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000371 delete init;
372 return NULL;
373 }
374}
375
376void Thread::Run() {
377 ProcessMessages(kForever);
378}
379
380bool Thread::IsOwned() {
381 return owned_;
382}
383
384void Thread::Stop() {
385 MessageQueue::Quit();
386 Join();
387}
388
389void Thread::Send(MessageHandler *phandler, uint32 id, MessageData *pdata) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000390 AssertBlockingIsAllowedOnCurrentThread();
391
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000392 if (fStop_)
393 return;
394
395 // Sent messages are sent to the MessageHandler directly, in the context
396 // of "thread", like Win32 SendMessage. If in the right context,
397 // call the handler directly.
398
399 Message msg;
400 msg.phandler = phandler;
401 msg.message_id = id;
402 msg.pdata = pdata;
403 if (IsCurrent()) {
404 phandler->OnMessage(&msg);
405 return;
406 }
407
408 AutoThread thread;
409 Thread *current_thread = Thread::Current();
410 ASSERT(current_thread != NULL); // AutoThread ensures this
411
412 bool ready = false;
413 {
414 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000415 _SendMessage smsg;
416 smsg.thread = current_thread;
417 smsg.msg = msg;
418 smsg.ready = &ready;
419 sendlist_.push_back(smsg);
420 }
421
422 // Wait for a reply
423
424 ss_->WakeUp();
425
426 bool waited = false;
427 crit_.Enter();
428 while (!ready) {
429 crit_.Leave();
430 current_thread->ReceiveSends();
431 current_thread->socketserver()->Wait(kForever, false);
432 waited = true;
433 crit_.Enter();
434 }
435 crit_.Leave();
436
437 // Our Wait loop above may have consumed some WakeUp events for this
438 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
439 // cause problems for some SocketServers.
440 //
441 // Concrete example:
442 // Win32SocketServer on thread A calls Send on thread B. While processing the
443 // message, thread B Posts a message to A. We consume the wakeup for that
444 // Post while waiting for the Send to complete, which means that when we exit
445 // this loop, we need to issue another WakeUp, or else the Posted message
446 // won't be processed in a timely manner.
447
448 if (waited) {
449 current_thread->socketserver()->WakeUp();
450 }
451}
452
453void Thread::ReceiveSends() {
454 // Receive a sent message. Cleanup scenarios:
455 // - thread sending exits: We don't allow this, since thread can exit
456 // only via Join, so Send must complete.
457 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
458 // - object target cleared: Wakeup/set ready in Thread::Clear()
459 crit_.Enter();
460 while (!sendlist_.empty()) {
461 _SendMessage smsg = sendlist_.front();
462 sendlist_.pop_front();
463 crit_.Leave();
464 smsg.msg.phandler->OnMessage(&smsg.msg);
465 crit_.Enter();
466 *smsg.ready = true;
467 smsg.thread->socketserver()->WakeUp();
468 }
469 crit_.Leave();
470}
471
472void Thread::Clear(MessageHandler *phandler, uint32 id,
473 MessageList* removed) {
474 CritScope cs(&crit_);
475
476 // Remove messages on sendlist_ with phandler
477 // Object target cleared: remove from send list, wakeup/set ready
478 // if sender not NULL.
479
480 std::list<_SendMessage>::iterator iter = sendlist_.begin();
481 while (iter != sendlist_.end()) {
482 _SendMessage smsg = *iter;
483 if (smsg.msg.Match(phandler, id)) {
484 if (removed) {
485 removed->push_back(smsg.msg);
486 } else {
487 delete smsg.msg.pdata;
488 }
489 iter = sendlist_.erase(iter);
490 *smsg.ready = true;
491 smsg.thread->socketserver()->WakeUp();
492 continue;
493 }
494 ++iter;
495 }
496
497 MessageQueue::Clear(phandler, id, removed);
498}
499
500bool Thread::ProcessMessages(int cmsLoop) {
501 uint32 msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
502 int cmsNext = cmsLoop;
503
504 while (true) {
505#if __has_feature(objc_arc)
506 @autoreleasepool
507#elif defined(WEBRTC_MAC)
508 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
509 // Each thread is supposed to have an autorelease pool. Also for event loops
510 // like this, autorelease pool needs to be created and drained/released
511 // for each cycle.
512 ScopedAutoreleasePool pool;
513#endif
514 {
515 Message msg;
516 if (!Get(&msg, cmsNext))
517 return !IsQuitting();
518 Dispatch(&msg);
519
520 if (cmsLoop != kForever) {
521 cmsNext = TimeUntil(msEnd);
522 if (cmsNext < 0)
523 return true;
524 }
525 }
526 }
527}
528
529bool Thread::WrapCurrent() {
530 return WrapCurrentWithThreadManager(ThreadManager::Instance());
531}
532
533bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000534 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535 return false;
536#if defined(WEBRTC_WIN)
537 // We explicitly ask for no rights other than synchronization.
538 // This gives us the best chance of succeeding.
539 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
540 if (!thread_) {
541 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
542 return false;
543 }
544 thread_id_ = GetCurrentThreadId();
545#elif defined(WEBRTC_POSIX)
546 thread_ = pthread_self();
547#endif
548 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000549 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000550 thread_manager->SetCurrentThread(this);
551 return true;
552}
553
554void Thread::UnwrapCurrent() {
555 // Clears the platform-specific thread-specific storage.
556 ThreadManager::Instance()->SetCurrentThread(NULL);
557#if defined(WEBRTC_WIN)
558 if (!CloseHandle(thread_)) {
559 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
560 }
561#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000562 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000563}
564
565
566AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
567 if (!ThreadManager::Instance()->CurrentThread()) {
568 ThreadManager::Instance()->SetCurrentThread(this);
569 }
570}
571
572AutoThread::~AutoThread() {
573 Stop();
574 if (ThreadManager::Instance()->CurrentThread() == this) {
575 ThreadManager::Instance()->SetCurrentThread(NULL);
576 }
577}
578
579#if defined(WEBRTC_WIN)
580void ComThread::Run() {
581 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
582 ASSERT(SUCCEEDED(hr));
583 if (SUCCEEDED(hr)) {
584 Thread::Run();
585 CoUninitialize();
586 } else {
587 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
588 }
589}
590#endif
591
592} // namespace rtc