2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
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.
11 #include "webrtc/base/thread.h"
14 #define __has_feature(x) 0 // Compatibility with non-clang or LLVM compilers.
15 #endif // __has_feature
17 #if defined(WEBRTC_WIN)
19 #elif defined(WEBRTC_POSIX)
23 #include "webrtc/base/common.h"
24 #include "webrtc/base/logging.h"
25 #include "webrtc/base/stringutils.h"
26 #include "webrtc/base/timeutils.h"
28 #if !__has_feature(objc_arc) && (defined(WEBRTC_MAC))
29 #include "webrtc/base/maccocoathreadhelper.h"
30 #include "webrtc/base/scoped_autorelease_pool.h"
35 ThreadManager* ThreadManager::Instance() {
36 LIBJINGLE_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
37 return &thread_manager;
41 Thread* Thread::Current() {
42 return ThreadManager::Instance()->CurrentThread();
45 #if defined(WEBRTC_POSIX)
46 ThreadManager::ThreadManager() {
47 pthread_key_create(&key_, NULL);
48 #ifndef NO_MAIN_THREAD_WRAPPING
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();
60 ThreadManager::~ThreadManager() {
61 #if __has_feature(objc_arc)
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;
70 UnwrapCurrentThread();
71 pthread_key_delete(key_);
75 Thread *ThreadManager::CurrentThread() {
76 return static_cast<Thread *>(pthread_getspecific(key_));
79 void ThreadManager::SetCurrentThread(Thread *thread) {
80 pthread_setspecific(key_, thread);
84 #if defined(WEBRTC_WIN)
85 ThreadManager::ThreadManager() {
87 #ifndef NO_MAIN_THREAD_WRAPPING
92 ThreadManager::~ThreadManager() {
93 UnwrapCurrentThread();
97 Thread *ThreadManager::CurrentThread() {
98 return static_cast<Thread *>(TlsGetValue(key_));
101 void ThreadManager::SetCurrentThread(Thread *thread) {
102 TlsSetValue(key_, thread);
106 Thread *ThreadManager::WrapCurrentThread() {
107 Thread* result = CurrentThread();
108 if (NULL == result) {
109 result = new Thread();
110 result->WrapCurrentWithThreadManager(this, true);
115 void ThreadManager::UnwrapCurrentThread() {
116 Thread* t = CurrentThread();
117 if (t && !(t->IsOwned())) {
128 Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
129 : thread_(Thread::Current()),
130 previous_state_(thread_->SetAllowBlockingCalls(false)) {
133 Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
134 ASSERT(thread_->IsCurrent());
135 thread_->SetAllowBlockingCalls(previous_state_);
138 Thread::Thread(SocketServer* ss)
140 priority_(PRIORITY_NORMAL),
141 running_(true, false),
142 #if defined(WEBRTC_WIN)
147 blocking_calls_allowed_(true) {
148 SetName("Thread", this); // default name
156 bool Thread::SleepMs(int milliseconds) {
157 AssertBlockingIsAllowedOnCurrentThread();
159 #if defined(WEBRTC_WIN)
160 ::Sleep(milliseconds);
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.
166 ts.tv_sec = milliseconds / 1000;
167 ts.tv_nsec = (milliseconds % 1000) * 1000000;
168 int ret = nanosleep(&ts, NULL);
170 LOG_ERR(LS_WARNING) << "nanosleep() returning early";
177 bool Thread::SetName(const std::string& name, const void* obj) {
178 if (running()) return false;
182 sprintfn(buf, sizeof(buf), " 0x%p", obj);
188 bool Thread::SetPriority(ThreadPriority priority) {
189 #if defined(WEBRTC_WIN)
191 ASSERT(thread_ != NULL);
193 if (priority == PRIORITY_NORMAL) {
194 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_NORMAL);
195 } else if (priority == PRIORITY_HIGH) {
196 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_HIGHEST);
197 } else if (priority == PRIORITY_ABOVE_NORMAL) {
198 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL);
199 } else if (priority == PRIORITY_IDLE) {
200 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_IDLE);
206 priority_ = priority;
209 // TODO: Implement for Linux/Mac if possible.
210 if (running()) return false;
211 priority_ = priority;
216 bool Thread::Start(Runnable* runnable) {
218 if (!owned_) return false;
220 if (running()) return false;
222 Restart(); // reset fStop_ if the thread is being restarted
224 // Make sure that ThreadManager is created on the main thread before
225 // we start a new thread.
226 ThreadManager::Instance();
228 ThreadInit* init = new ThreadInit;
230 init->runnable = runnable;
231 #if defined(WEBRTC_WIN)
233 if (priority_ != PRIORITY_NORMAL) {
234 flags = CREATE_SUSPENDED;
236 thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PreRun, init, flags,
240 if (priority_ != PRIORITY_NORMAL) {
241 SetPriority(priority_);
242 ::ResumeThread(thread_);
247 #elif defined(WEBRTC_POSIX)
249 pthread_attr_init(&attr);
251 // Thread priorities are not supported in NaCl.
252 #if !defined(__native_client__)
253 if (priority_ != PRIORITY_NORMAL) {
254 if (priority_ == PRIORITY_IDLE) {
255 // There is no POSIX-standard way to set a below-normal priority for an
256 // individual thread (only whole process), so let's not support it.
257 LOG(LS_WARNING) << "PRIORITY_IDLE not supported";
259 // Set real-time round-robin policy.
260 if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0) {
261 LOG(LS_ERROR) << "pthread_attr_setschedpolicy";
263 struct sched_param param;
264 if (pthread_attr_getschedparam(&attr, ¶m) != 0) {
265 LOG(LS_ERROR) << "pthread_attr_getschedparam";
267 // The numbers here are arbitrary.
268 if (priority_ == PRIORITY_HIGH) {
269 param.sched_priority = 6; // 6 = HIGH
271 ASSERT(priority_ == PRIORITY_ABOVE_NORMAL);
272 param.sched_priority = 4; // 4 = ABOVE_NORMAL
274 if (pthread_attr_setschedparam(&attr, ¶m) != 0) {
275 LOG(LS_ERROR) << "pthread_attr_setschedparam";
280 #endif // !defined(__native_client__)
282 int error_code = pthread_create(&thread_, &attr, PreRun, init);
283 if (0 != error_code) {
284 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
292 bool Thread::WrapCurrent() {
293 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
296 void Thread::UnwrapCurrent() {
297 // Clears the platform-specific thread-specific storage.
298 ThreadManager::Instance()->SetCurrentThread(NULL);
299 #if defined(WEBRTC_WIN)
300 if (thread_ != NULL) {
301 if (!CloseHandle(thread_)) {
302 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
310 void Thread::SafeWrapCurrent() {
311 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
314 void Thread::Join() {
315 AssertBlockingIsAllowedOnCurrentThread();
318 ASSERT(!IsCurrent());
319 #if defined(WEBRTC_WIN)
320 ASSERT(thread_ != NULL);
321 WaitForSingleObject(thread_, INFINITE);
322 CloseHandle(thread_);
325 #elif defined(WEBRTC_POSIX)
327 pthread_join(thread_, &pv);
333 bool Thread::SetAllowBlockingCalls(bool allow) {
335 bool previous = blocking_calls_allowed_;
336 blocking_calls_allowed_ = allow;
341 void Thread::AssertBlockingIsAllowedOnCurrentThread() {
343 Thread* current = Thread::Current();
344 ASSERT(!current || current->blocking_calls_allowed_);
348 #if defined(WEBRTC_WIN)
350 // http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx
351 #define MSDEV_SET_THREAD_NAME 0x406D1388
352 typedef struct tagTHREADNAME_INFO {
359 void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) {
360 THREADNAME_INFO info;
361 info.dwType = 0x1000;
362 info.szName = szThreadName;
363 info.dwThreadID = dwThreadID;
367 RaiseException(MSDEV_SET_THREAD_NAME, 0, sizeof(info) / sizeof(DWORD),
368 reinterpret_cast<ULONG_PTR*>(&info));
370 __except(EXCEPTION_CONTINUE_EXECUTION) {
375 void* Thread::PreRun(void* pv) {
376 ThreadInit* init = static_cast<ThreadInit*>(pv);
377 ThreadManager::Instance()->SetCurrentThread(init->thread);
378 #if defined(WEBRTC_WIN)
379 SetThreadName(GetCurrentThreadId(), init->thread->name_.c_str());
380 #elif defined(WEBRTC_POSIX)
381 // TODO: See if naming exists for pthreads.
383 #if __has_feature(objc_arc)
385 #elif defined(WEBRTC_MAC)
386 // Make sure the new thread has an autoreleasepool
387 ScopedAutoreleasePool pool;
390 if (init->runnable) {
391 init->runnable->Run(init->thread);
401 ProcessMessages(kForever);
404 bool Thread::IsOwned() {
408 void Thread::Stop() {
409 MessageQueue::Quit();
413 void Thread::Send(MessageHandler *phandler, uint32 id, MessageData *pdata) {
417 // Sent messages are sent to the MessageHandler directly, in the context
418 // of "thread", like Win32 SendMessage. If in the right context,
419 // call the handler directly.
421 msg.phandler = phandler;
425 phandler->OnMessage(&msg);
429 AssertBlockingIsAllowedOnCurrentThread();
432 Thread *current_thread = Thread::Current();
433 ASSERT(current_thread != NULL); // AutoThread ensures this
437 CritScope cs(&crit_);
439 smsg.thread = current_thread;
442 sendlist_.push_back(smsg);
453 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
454 // thread invoking calls on the current thread.
455 current_thread->ReceiveSendsFromThread(this);
456 current_thread->socketserver()->Wait(kForever, false);
462 // Our Wait loop above may have consumed some WakeUp events for this
463 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
464 // cause problems for some SocketServers.
467 // Win32SocketServer on thread A calls Send on thread B. While processing the
468 // message, thread B Posts a message to A. We consume the wakeup for that
469 // Post while waiting for the Send to complete, which means that when we exit
470 // this loop, we need to issue another WakeUp, or else the Posted message
471 // won't be processed in a timely manner.
474 current_thread->socketserver()->WakeUp();
478 void Thread::ReceiveSends() {
479 ReceiveSendsFromThread(NULL);
482 void Thread::ReceiveSendsFromThread(const Thread* source) {
483 // Receive a sent message. Cleanup scenarios:
484 // - thread sending exits: We don't allow this, since thread can exit
485 // only via Join, so Send must complete.
486 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
487 // - object target cleared: Wakeup/set ready in Thread::Clear()
491 while (PopSendMessageFromThread(source, &smsg)) {
494 smsg.msg.phandler->OnMessage(&smsg.msg);
498 smsg.thread->socketserver()->WakeUp();
503 bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
504 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
505 it != sendlist_.end(); ++it) {
506 if (it->thread == source || source == NULL) {
515 void Thread::Clear(MessageHandler *phandler, uint32 id,
516 MessageList* removed) {
517 CritScope cs(&crit_);
519 // Remove messages on sendlist_ with phandler
520 // Object target cleared: remove from send list, wakeup/set ready
521 // if sender not NULL.
523 std::list<_SendMessage>::iterator iter = sendlist_.begin();
524 while (iter != sendlist_.end()) {
525 _SendMessage smsg = *iter;
526 if (smsg.msg.Match(phandler, id)) {
528 removed->push_back(smsg.msg);
530 delete smsg.msg.pdata;
532 iter = sendlist_.erase(iter);
534 smsg.thread->socketserver()->WakeUp();
540 MessageQueue::Clear(phandler, id, removed);
543 bool Thread::ProcessMessages(int cmsLoop) {
544 uint32 msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
545 int cmsNext = cmsLoop;
548 #if __has_feature(objc_arc)
550 #elif defined(WEBRTC_MAC)
551 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
552 // Each thread is supposed to have an autorelease pool. Also for event loops
553 // like this, autorelease pool needs to be created and drained/released
555 ScopedAutoreleasePool pool;
559 if (!Get(&msg, cmsNext))
560 return !IsQuitting();
563 if (cmsLoop != kForever) {
564 cmsNext = TimeUntil(msEnd);
572 bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
573 bool need_synchronize_access) {
577 #if defined(WEBRTC_WIN)
578 if (need_synchronize_access) {
579 // We explicitly ask for no rights other than synchronization.
580 // This gives us the best chance of succeeding.
581 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
583 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
586 thread_id_ = GetCurrentThreadId();
588 #elif defined(WEBRTC_POSIX)
589 thread_ = pthread_self();
594 thread_manager->SetCurrentThread(this);
598 AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
599 if (!ThreadManager::Instance()->CurrentThread()) {
600 ThreadManager::Instance()->SetCurrentThread(this);
604 AutoThread::~AutoThread() {
606 if (ThreadManager::Instance()->CurrentThread() == this) {
607 ThreadManager::Instance()->SetCurrentThread(NULL);
611 #if defined(WEBRTC_WIN)
612 void ComThread::Run() {
613 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
614 ASSERT(SUCCEEDED(hr));
619 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;