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