blob: 3963b3886a2daf6ca1d1c92b98de7b75421d949a [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
128Thread::Thread(SocketServer* ss)
129 : MessageQueue(ss),
130 priority_(PRIORITY_NORMAL),
131 started_(false),
132#if defined(WEBRTC_WIN)
133 thread_(NULL),
134 thread_id_(0),
135#endif
136 owned_(true),
137 delete_self_when_complete_(false) {
138 SetName("Thread", this); // default name
139}
140
141Thread::~Thread() {
142 Stop();
henrike@webrtc.org99b41622014-05-21 20:42:17 +0000143 Clear(NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144}
145
146bool Thread::SleepMs(int milliseconds) {
147#if defined(WEBRTC_WIN)
148 ::Sleep(milliseconds);
149 return true;
150#else
151 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
152 // so we use nanosleep() even though it has greater precision than necessary.
153 struct timespec ts;
154 ts.tv_sec = milliseconds / 1000;
155 ts.tv_nsec = (milliseconds % 1000) * 1000000;
156 int ret = nanosleep(&ts, NULL);
157 if (ret != 0) {
158 LOG_ERR(LS_WARNING) << "nanosleep() returning early";
159 return false;
160 }
161 return true;
162#endif
163}
164
165bool Thread::SetName(const std::string& name, const void* obj) {
166 if (started_) return false;
167 name_ = name;
168 if (obj) {
169 char buf[16];
170 sprintfn(buf, sizeof(buf), " 0x%p", obj);
171 name_ += buf;
172 }
173 return true;
174}
175
176bool Thread::SetPriority(ThreadPriority priority) {
177#if defined(WEBRTC_WIN)
178 if (started_) {
179 BOOL ret = FALSE;
180 if (priority == PRIORITY_NORMAL) {
181 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_NORMAL);
182 } else if (priority == PRIORITY_HIGH) {
183 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_HIGHEST);
184 } else if (priority == PRIORITY_ABOVE_NORMAL) {
185 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL);
186 } else if (priority == PRIORITY_IDLE) {
187 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_IDLE);
188 }
189 if (!ret) {
190 return false;
191 }
192 }
193 priority_ = priority;
194 return true;
195#else
196 // TODO: Implement for Linux/Mac if possible.
197 if (started_) return false;
198 priority_ = priority;
199 return true;
200#endif
201}
202
203bool Thread::Start(Runnable* runnable) {
204 ASSERT(owned_);
205 if (!owned_) return false;
206 ASSERT(!started_);
207 if (started_) return false;
208
209 Restart(); // reset fStop_ if the thread is being restarted
210
211 // Make sure that ThreadManager is created on the main thread before
212 // we start a new thread.
213 ThreadManager::Instance();
214
215 ThreadInit* init = new ThreadInit;
216 init->thread = this;
217 init->runnable = runnable;
218#if defined(WEBRTC_WIN)
219 DWORD flags = 0;
220 if (priority_ != PRIORITY_NORMAL) {
221 flags = CREATE_SUSPENDED;
222 }
223 thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PreRun, init, flags,
224 &thread_id_);
225 if (thread_) {
226 started_ = true;
227 if (priority_ != PRIORITY_NORMAL) {
228 SetPriority(priority_);
229 ::ResumeThread(thread_);
230 }
231 } else {
232 return false;
233 }
234#elif defined(WEBRTC_POSIX)
235 pthread_attr_t attr;
236 pthread_attr_init(&attr);
237
238 // Thread priorities are not supported in NaCl.
239#if !defined(__native_client__)
240 if (priority_ != PRIORITY_NORMAL) {
241 if (priority_ == PRIORITY_IDLE) {
242 // There is no POSIX-standard way to set a below-normal priority for an
243 // individual thread (only whole process), so let's not support it.
244 LOG(LS_WARNING) << "PRIORITY_IDLE not supported";
245 } else {
246 // Set real-time round-robin policy.
247 if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0) {
248 LOG(LS_ERROR) << "pthread_attr_setschedpolicy";
249 }
250 struct sched_param param;
251 if (pthread_attr_getschedparam(&attr, &param) != 0) {
252 LOG(LS_ERROR) << "pthread_attr_getschedparam";
253 } else {
254 // The numbers here are arbitrary.
255 if (priority_ == PRIORITY_HIGH) {
256 param.sched_priority = 6; // 6 = HIGH
257 } else {
258 ASSERT(priority_ == PRIORITY_ABOVE_NORMAL);
259 param.sched_priority = 4; // 4 = ABOVE_NORMAL
260 }
261 if (pthread_attr_setschedparam(&attr, &param) != 0) {
262 LOG(LS_ERROR) << "pthread_attr_setschedparam";
263 }
264 }
265 }
266 }
267#endif // !defined(__native_client__)
268
269 int error_code = pthread_create(&thread_, &attr, PreRun, init);
270 if (0 != error_code) {
271 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
272 return false;
273 }
274 started_ = true;
275#endif
276 return true;
277}
278
279void Thread::Join() {
280 if (started_) {
281 ASSERT(!IsCurrent());
282#if defined(WEBRTC_WIN)
283 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
291 started_ = false;
292 }
293}
294
295#if defined(WEBRTC_WIN)
296// As seen on MSDN.
297// http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx
298#define MSDEV_SET_THREAD_NAME 0x406D1388
299typedef struct tagTHREADNAME_INFO {
300 DWORD dwType;
301 LPCSTR szName;
302 DWORD dwThreadID;
303 DWORD dwFlags;
304} THREADNAME_INFO;
305
306void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) {
307 THREADNAME_INFO info;
308 info.dwType = 0x1000;
309 info.szName = szThreadName;
310 info.dwThreadID = dwThreadID;
311 info.dwFlags = 0;
312
313 __try {
314 RaiseException(MSDEV_SET_THREAD_NAME, 0, sizeof(info) / sizeof(DWORD),
315 reinterpret_cast<ULONG_PTR*>(&info));
316 }
317 __except(EXCEPTION_CONTINUE_EXECUTION) {
318 }
319}
320#endif // WEBRTC_WIN
321
322void* Thread::PreRun(void* pv) {
323 ThreadInit* init = static_cast<ThreadInit*>(pv);
324 ThreadManager::Instance()->SetCurrentThread(init->thread);
325#if defined(WEBRTC_WIN)
326 SetThreadName(GetCurrentThreadId(), init->thread->name_.c_str());
327#elif defined(WEBRTC_POSIX)
328 // TODO: See if naming exists for pthreads.
329#endif
330#if __has_feature(objc_arc)
331 @autoreleasepool
332#elif defined(WEBRTC_MAC)
333 // Make sure the new thread has an autoreleasepool
334 ScopedAutoreleasePool pool;
335#endif
336 {
337 if (init->runnable) {
338 init->runnable->Run(init->thread);
339 } else {
340 init->thread->Run();
341 }
342 if (init->thread->delete_self_when_complete_) {
343 init->thread->started_ = false;
344 delete init->thread;
345 }
346 delete init;
347 return NULL;
348 }
349}
350
351void Thread::Run() {
352 ProcessMessages(kForever);
353}
354
355bool Thread::IsOwned() {
356 return owned_;
357}
358
359void Thread::Stop() {
360 MessageQueue::Quit();
361 Join();
362}
363
364void Thread::Send(MessageHandler *phandler, uint32 id, MessageData *pdata) {
365 if (fStop_)
366 return;
367
368 // Sent messages are sent to the MessageHandler directly, in the context
369 // of "thread", like Win32 SendMessage. If in the right context,
370 // call the handler directly.
371
372 Message msg;
373 msg.phandler = phandler;
374 msg.message_id = id;
375 msg.pdata = pdata;
376 if (IsCurrent()) {
377 phandler->OnMessage(&msg);
378 return;
379 }
380
381 AutoThread thread;
382 Thread *current_thread = Thread::Current();
383 ASSERT(current_thread != NULL); // AutoThread ensures this
384
385 bool ready = false;
386 {
387 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000388 _SendMessage smsg;
389 smsg.thread = current_thread;
390 smsg.msg = msg;
391 smsg.ready = &ready;
392 sendlist_.push_back(smsg);
393 }
394
395 // Wait for a reply
396
397 ss_->WakeUp();
398
399 bool waited = false;
400 crit_.Enter();
401 while (!ready) {
402 crit_.Leave();
403 current_thread->ReceiveSends();
404 current_thread->socketserver()->Wait(kForever, false);
405 waited = true;
406 crit_.Enter();
407 }
408 crit_.Leave();
409
410 // Our Wait loop above may have consumed some WakeUp events for this
411 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
412 // cause problems for some SocketServers.
413 //
414 // Concrete example:
415 // Win32SocketServer on thread A calls Send on thread B. While processing the
416 // message, thread B Posts a message to A. We consume the wakeup for that
417 // Post while waiting for the Send to complete, which means that when we exit
418 // this loop, we need to issue another WakeUp, or else the Posted message
419 // won't be processed in a timely manner.
420
421 if (waited) {
422 current_thread->socketserver()->WakeUp();
423 }
424}
425
426void Thread::ReceiveSends() {
427 // Receive a sent message. Cleanup scenarios:
428 // - thread sending exits: We don't allow this, since thread can exit
429 // only via Join, so Send must complete.
430 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
431 // - object target cleared: Wakeup/set ready in Thread::Clear()
432 crit_.Enter();
433 while (!sendlist_.empty()) {
434 _SendMessage smsg = sendlist_.front();
435 sendlist_.pop_front();
436 crit_.Leave();
437 smsg.msg.phandler->OnMessage(&smsg.msg);
438 crit_.Enter();
439 *smsg.ready = true;
440 smsg.thread->socketserver()->WakeUp();
441 }
442 crit_.Leave();
443}
444
445void Thread::Clear(MessageHandler *phandler, uint32 id,
446 MessageList* removed) {
447 CritScope cs(&crit_);
448
449 // Remove messages on sendlist_ with phandler
450 // Object target cleared: remove from send list, wakeup/set ready
451 // if sender not NULL.
452
453 std::list<_SendMessage>::iterator iter = sendlist_.begin();
454 while (iter != sendlist_.end()) {
455 _SendMessage smsg = *iter;
456 if (smsg.msg.Match(phandler, id)) {
457 if (removed) {
458 removed->push_back(smsg.msg);
459 } else {
460 delete smsg.msg.pdata;
461 }
462 iter = sendlist_.erase(iter);
463 *smsg.ready = true;
464 smsg.thread->socketserver()->WakeUp();
465 continue;
466 }
467 ++iter;
468 }
469
470 MessageQueue::Clear(phandler, id, removed);
471}
472
473bool Thread::ProcessMessages(int cmsLoop) {
474 uint32 msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
475 int cmsNext = cmsLoop;
476
477 while (true) {
478#if __has_feature(objc_arc)
479 @autoreleasepool
480#elif defined(WEBRTC_MAC)
481 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
482 // Each thread is supposed to have an autorelease pool. Also for event loops
483 // like this, autorelease pool needs to be created and drained/released
484 // for each cycle.
485 ScopedAutoreleasePool pool;
486#endif
487 {
488 Message msg;
489 if (!Get(&msg, cmsNext))
490 return !IsQuitting();
491 Dispatch(&msg);
492
493 if (cmsLoop != kForever) {
494 cmsNext = TimeUntil(msEnd);
495 if (cmsNext < 0)
496 return true;
497 }
498 }
499 }
500}
501
502bool Thread::WrapCurrent() {
503 return WrapCurrentWithThreadManager(ThreadManager::Instance());
504}
505
506bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager) {
507 if (started_)
508 return false;
509#if defined(WEBRTC_WIN)
510 // We explicitly ask for no rights other than synchronization.
511 // This gives us the best chance of succeeding.
512 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
513 if (!thread_) {
514 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
515 return false;
516 }
517 thread_id_ = GetCurrentThreadId();
518#elif defined(WEBRTC_POSIX)
519 thread_ = pthread_self();
520#endif
521 owned_ = false;
522 started_ = true;
523 thread_manager->SetCurrentThread(this);
524 return true;
525}
526
527void Thread::UnwrapCurrent() {
528 // Clears the platform-specific thread-specific storage.
529 ThreadManager::Instance()->SetCurrentThread(NULL);
530#if defined(WEBRTC_WIN)
531 if (!CloseHandle(thread_)) {
532 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
533 }
534#endif
535 started_ = false;
536}
537
538
539AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
540 if (!ThreadManager::Instance()->CurrentThread()) {
541 ThreadManager::Instance()->SetCurrentThread(this);
542 }
543}
544
545AutoThread::~AutoThread() {
546 Stop();
547 if (ThreadManager::Instance()->CurrentThread() == this) {
548 ThreadManager::Instance()->SetCurrentThread(NULL);
549 }
550}
551
552#if defined(WEBRTC_WIN)
553void ComThread::Run() {
554 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
555 ASSERT(SUCCEEDED(hr));
556 if (SUCCEEDED(hr)) {
557 Thread::Run();
558 CoUninitialize();
559 } else {
560 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
561 }
562}
563#endif
564
565} // namespace rtc