blob: 9d2917d9a02d795c48783fed01338ed5b32e769e [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();
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000110 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 }
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()) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000191 ASSERT(thread_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000192 BOOL ret = FALSE;
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);
201 }
202 if (!ret) {
203 return false;
204 }
205 }
206 priority_ = priority;
207 return true;
208#else
209 // TODO: Implement for Linux/Mac if possible.
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000210 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000211 priority_ = priority;
212 return true;
213#endif
214}
215
216bool Thread::Start(Runnable* runnable) {
217 ASSERT(owned_);
218 if (!owned_) return false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000219 ASSERT(!running());
220 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000221
222 Restart(); // reset fStop_ if the thread is being restarted
223
224 // Make sure that ThreadManager is created on the main thread before
225 // we start a new thread.
226 ThreadManager::Instance();
227
228 ThreadInit* init = new ThreadInit;
229 init->thread = this;
230 init->runnable = runnable;
231#if defined(WEBRTC_WIN)
232 DWORD flags = 0;
233 if (priority_ != PRIORITY_NORMAL) {
234 flags = CREATE_SUSPENDED;
235 }
236 thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PreRun, init, flags,
237 &thread_id_);
238 if (thread_) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000239 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240 if (priority_ != PRIORITY_NORMAL) {
241 SetPriority(priority_);
242 ::ResumeThread(thread_);
243 }
244 } else {
245 return false;
246 }
247#elif defined(WEBRTC_POSIX)
248 pthread_attr_t attr;
249 pthread_attr_init(&attr);
250
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";
258 } else {
259 // Set real-time round-robin policy.
260 if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0) {
261 LOG(LS_ERROR) << "pthread_attr_setschedpolicy";
262 }
263 struct sched_param param;
264 if (pthread_attr_getschedparam(&attr, &param) != 0) {
265 LOG(LS_ERROR) << "pthread_attr_getschedparam";
266 } else {
267 // The numbers here are arbitrary.
268 if (priority_ == PRIORITY_HIGH) {
269 param.sched_priority = 6; // 6 = HIGH
270 } else {
271 ASSERT(priority_ == PRIORITY_ABOVE_NORMAL);
272 param.sched_priority = 4; // 4 = ABOVE_NORMAL
273 }
274 if (pthread_attr_setschedparam(&attr, &param) != 0) {
275 LOG(LS_ERROR) << "pthread_attr_setschedparam";
276 }
277 }
278 }
279 }
280#endif // !defined(__native_client__)
281
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;
285 return false;
286 }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000287 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000288#endif
289 return true;
290}
291
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000292bool Thread::WrapCurrent() {
293 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
294}
295
296void 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.";
303 }
304 thread_ = NULL;
305 }
306#endif
307 running_.Reset();
308}
309
310void Thread::SafeWrapCurrent() {
311 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
312}
313
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314void Thread::Join() {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000315 AssertBlockingIsAllowedOnCurrentThread();
316
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000317 if (running()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000318 ASSERT(!IsCurrent());
319#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000320 ASSERT(thread_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321 WaitForSingleObject(thread_, INFINITE);
322 CloseHandle(thread_);
323 thread_ = NULL;
324 thread_id_ = 0;
325#elif defined(WEBRTC_POSIX)
326 void *pv;
327 pthread_join(thread_, &pv);
328#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000329 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330 }
331}
332
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000333bool Thread::SetAllowBlockingCalls(bool allow) {
334 ASSERT(IsCurrent());
335 bool previous = blocking_calls_allowed_;
336 blocking_calls_allowed_ = allow;
337 return previous;
338}
339
340// static
341void Thread::AssertBlockingIsAllowedOnCurrentThread() {
342#ifdef _DEBUG
343 Thread* current = Thread::Current();
344 ASSERT(!current || current->blocking_calls_allowed_);
345#endif
346}
347
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348#if defined(WEBRTC_WIN)
349// As seen on MSDN.
350// http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx
351#define MSDEV_SET_THREAD_NAME 0x406D1388
352typedef struct tagTHREADNAME_INFO {
353 DWORD dwType;
354 LPCSTR szName;
355 DWORD dwThreadID;
356 DWORD dwFlags;
357} THREADNAME_INFO;
358
359void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) {
360 THREADNAME_INFO info;
361 info.dwType = 0x1000;
362 info.szName = szThreadName;
363 info.dwThreadID = dwThreadID;
364 info.dwFlags = 0;
365
366 __try {
367 RaiseException(MSDEV_SET_THREAD_NAME, 0, sizeof(info) / sizeof(DWORD),
368 reinterpret_cast<ULONG_PTR*>(&info));
369 }
370 __except(EXCEPTION_CONTINUE_EXECUTION) {
371 }
372}
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000373#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000374
375void* 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.
382#endif
383#if __has_feature(objc_arc)
384 @autoreleasepool
385#elif defined(WEBRTC_MAC)
386 // Make sure the new thread has an autoreleasepool
387 ScopedAutoreleasePool pool;
388#endif
389 {
390 if (init->runnable) {
391 init->runnable->Run(init->thread);
392 } else {
393 init->thread->Run();
394 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000395 delete init;
396 return NULL;
397 }
398}
399
400void Thread::Run() {
401 ProcessMessages(kForever);
402}
403
404bool Thread::IsOwned() {
405 return owned_;
406}
407
408void Thread::Stop() {
409 MessageQueue::Quit();
410 Join();
411}
412
413void Thread::Send(MessageHandler *phandler, uint32 id, MessageData *pdata) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000414 AssertBlockingIsAllowedOnCurrentThread();
415
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000416 if (fStop_)
417 return;
418
419 // Sent messages are sent to the MessageHandler directly, in the context
420 // of "thread", like Win32 SendMessage. If in the right context,
421 // call the handler directly.
422
423 Message msg;
424 msg.phandler = phandler;
425 msg.message_id = id;
426 msg.pdata = pdata;
427 if (IsCurrent()) {
428 phandler->OnMessage(&msg);
429 return;
430 }
431
432 AutoThread thread;
433 Thread *current_thread = Thread::Current();
434 ASSERT(current_thread != NULL); // AutoThread ensures this
435
436 bool ready = false;
437 {
438 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000439 _SendMessage smsg;
440 smsg.thread = current_thread;
441 smsg.msg = msg;
442 smsg.ready = &ready;
443 sendlist_.push_back(smsg);
444 }
445
446 // Wait for a reply
447
448 ss_->WakeUp();
449
450 bool waited = false;
451 crit_.Enter();
452 while (!ready) {
453 crit_.Leave();
454 current_thread->ReceiveSends();
455 current_thread->socketserver()->Wait(kForever, false);
456 waited = true;
457 crit_.Enter();
458 }
459 crit_.Leave();
460
461 // Our Wait loop above may have consumed some WakeUp events for this
462 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
463 // cause problems for some SocketServers.
464 //
465 // Concrete example:
466 // Win32SocketServer on thread A calls Send on thread B. While processing the
467 // message, thread B Posts a message to A. We consume the wakeup for that
468 // Post while waiting for the Send to complete, which means that when we exit
469 // this loop, we need to issue another WakeUp, or else the Posted message
470 // won't be processed in a timely manner.
471
472 if (waited) {
473 current_thread->socketserver()->WakeUp();
474 }
475}
476
477void Thread::ReceiveSends() {
478 // Receive a sent message. Cleanup scenarios:
479 // - thread sending exits: We don't allow this, since thread can exit
480 // only via Join, so Send must complete.
481 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
482 // - object target cleared: Wakeup/set ready in Thread::Clear()
483 crit_.Enter();
484 while (!sendlist_.empty()) {
485 _SendMessage smsg = sendlist_.front();
486 sendlist_.pop_front();
487 crit_.Leave();
488 smsg.msg.phandler->OnMessage(&smsg.msg);
489 crit_.Enter();
490 *smsg.ready = true;
491 smsg.thread->socketserver()->WakeUp();
492 }
493 crit_.Leave();
494}
495
496void Thread::Clear(MessageHandler *phandler, uint32 id,
497 MessageList* removed) {
498 CritScope cs(&crit_);
499
500 // Remove messages on sendlist_ with phandler
501 // Object target cleared: remove from send list, wakeup/set ready
502 // if sender not NULL.
503
504 std::list<_SendMessage>::iterator iter = sendlist_.begin();
505 while (iter != sendlist_.end()) {
506 _SendMessage smsg = *iter;
507 if (smsg.msg.Match(phandler, id)) {
508 if (removed) {
509 removed->push_back(smsg.msg);
510 } else {
511 delete smsg.msg.pdata;
512 }
513 iter = sendlist_.erase(iter);
514 *smsg.ready = true;
515 smsg.thread->socketserver()->WakeUp();
516 continue;
517 }
518 ++iter;
519 }
520
521 MessageQueue::Clear(phandler, id, removed);
522}
523
524bool Thread::ProcessMessages(int cmsLoop) {
525 uint32 msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
526 int cmsNext = cmsLoop;
527
528 while (true) {
529#if __has_feature(objc_arc)
530 @autoreleasepool
531#elif defined(WEBRTC_MAC)
532 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
533 // Each thread is supposed to have an autorelease pool. Also for event loops
534 // like this, autorelease pool needs to be created and drained/released
535 // for each cycle.
536 ScopedAutoreleasePool pool;
537#endif
538 {
539 Message msg;
540 if (!Get(&msg, cmsNext))
541 return !IsQuitting();
542 Dispatch(&msg);
543
544 if (cmsLoop != kForever) {
545 cmsNext = TimeUntil(msEnd);
546 if (cmsNext < 0)
547 return true;
548 }
549 }
550 }
551}
552
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000553bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
554 bool need_synchronize_access) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000555 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000556 return false;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000557
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000558#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000559 if (need_synchronize_access) {
560 // We explicitly ask for no rights other than synchronization.
561 // This gives us the best chance of succeeding.
562 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
563 if (!thread_) {
564 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
565 return false;
566 }
567 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000568 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000569#elif defined(WEBRTC_POSIX)
570 thread_ = pthread_self();
571#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000572
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000573 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000574 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000575 thread_manager->SetCurrentThread(this);
576 return true;
577}
578
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000579AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
580 if (!ThreadManager::Instance()->CurrentThread()) {
581 ThreadManager::Instance()->SetCurrentThread(this);
582 }
583}
584
585AutoThread::~AutoThread() {
586 Stop();
587 if (ThreadManager::Instance()->CurrentThread() == this) {
588 ThreadManager::Instance()->SetCurrentThread(NULL);
589 }
590}
591
592#if defined(WEBRTC_WIN)
593void ComThread::Run() {
594 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
595 ASSERT(SUCCEEDED(hr));
596 if (SUCCEEDED(hr)) {
597 Thread::Run();
598 CoUninitialize();
599 } else {
600 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
601 }
602}
603#endif
604
605} // namespace rtc