blob: 87e4ffff614f9206c07804e375ab8b00e7f9b3b4 [file] [log] [blame]
henrike@webrtc.org0e118e72013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/base/thread.h"
29
30#ifndef __has_feature
31#define __has_feature(x) 0 // Compatibility with non-clang or LLVM compilers.
32#endif // __has_feature
33
34#if defined(WIN32)
35#include <comdef.h>
36#elif defined(POSIX)
37#include <time.h>
38#endif
39
40#include "talk/base/common.h"
41#include "talk/base/logging.h"
42#include "talk/base/stringutils.h"
43#include "talk/base/timeutils.h"
44
45#if !__has_feature(objc_arc) && (defined(OSX) || defined(IOS))
46#include "talk/base/maccocoathreadhelper.h"
47#include "talk/base/scoped_autorelease_pool.h"
48#endif
49
50namespace talk_base {
51
52ThreadManager* ThreadManager::Instance() {
53 LIBJINGLE_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
54 return &thread_manager;
55}
56
57// static
58Thread* Thread::Current() {
59 return ThreadManager::Instance()->CurrentThread();
60}
61
62#ifdef POSIX
63ThreadManager::ThreadManager() {
64 pthread_key_create(&key_, NULL);
65#ifndef NO_MAIN_THREAD_WRAPPING
66 WrapCurrentThread();
67#endif
68#if !__has_feature(objc_arc) && (defined(OSX) || defined(IOS))
69 // Under Automatic Reference Counting (ARC), you cannot use autorelease pools
70 // directly. Instead, you use @autoreleasepool blocks instead. Also, we are
71 // maintaining thread safety using immutability within context of GCD dispatch
72 // queues in this case.
73 InitCocoaMultiThreading();
74#endif
75}
76
77ThreadManager::~ThreadManager() {
78#if __has_feature(objc_arc)
79 @autoreleasepool
80#elif defined(OSX) || defined(IOS)
81 // This is called during exit, at which point apparently no NSAutoreleasePools
82 // are available; but we might still need them to do cleanup (or we get the
83 // "no autoreleasepool in place, just leaking" warning when exiting).
84 ScopedAutoreleasePool pool;
85#endif
86 {
87 UnwrapCurrentThread();
88 pthread_key_delete(key_);
89 }
90}
91
92Thread *ThreadManager::CurrentThread() {
93 return static_cast<Thread *>(pthread_getspecific(key_));
94}
95
96void ThreadManager::SetCurrentThread(Thread *thread) {
97 pthread_setspecific(key_, thread);
98}
99#endif
100
101#ifdef WIN32
102ThreadManager::ThreadManager() {
103 key_ = TlsAlloc();
104#ifndef NO_MAIN_THREAD_WRAPPING
105 WrapCurrentThread();
106#endif
107}
108
109ThreadManager::~ThreadManager() {
110 UnwrapCurrentThread();
111 TlsFree(key_);
112}
113
114Thread *ThreadManager::CurrentThread() {
115 return static_cast<Thread *>(TlsGetValue(key_));
116}
117
118void ThreadManager::SetCurrentThread(Thread *thread) {
119 TlsSetValue(key_, thread);
120}
121#endif
122
123Thread *ThreadManager::WrapCurrentThread() {
124 Thread* result = CurrentThread();
125 if (NULL == result) {
126 result = new Thread();
127 result->WrapCurrentWithThreadManager(this);
128 }
129 return result;
130}
131
132void ThreadManager::UnwrapCurrentThread() {
133 Thread* t = CurrentThread();
134 if (t && !(t->IsOwned())) {
135 t->UnwrapCurrent();
136 delete t;
137 }
138}
139
140struct ThreadInit {
141 Thread* thread;
142 Runnable* runnable;
143};
144
145Thread::Thread(SocketServer* ss)
146 : MessageQueue(ss),
147 priority_(PRIORITY_NORMAL),
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000148 running_(true, false),
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000149#if defined(WIN32)
150 thread_(NULL),
151 thread_id_(0),
152#endif
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000153 owned_(true) {
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000154 SetName("Thread", this); // default name
155}
156
157Thread::~Thread() {
158 Stop();
fischman@webrtc.org934c9032014-05-19 17:58:04 +0000159 Clear(NULL);
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000160}
161
162bool Thread::SleepMs(int milliseconds) {
163#ifdef WIN32
164 ::Sleep(milliseconds);
165 return true;
166#else
167 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
168 // so we use nanosleep() even though it has greater precision than necessary.
169 struct timespec ts;
170 ts.tv_sec = milliseconds / 1000;
171 ts.tv_nsec = (milliseconds % 1000) * 1000000;
172 int ret = nanosleep(&ts, NULL);
173 if (ret != 0) {
174 LOG_ERR(LS_WARNING) << "nanosleep() returning early";
175 return false;
176 }
177 return true;
178#endif
179}
180
181bool Thread::SetName(const std::string& name, const void* obj) {
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000182 if (running()) return false;
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000183 name_ = name;
184 if (obj) {
185 char buf[16];
186 sprintfn(buf, sizeof(buf), " 0x%p", obj);
187 name_ += buf;
188 }
189 return true;
190}
191
192bool Thread::SetPriority(ThreadPriority priority) {
193#if defined(WIN32)
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000194 if (running()) {
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000195 BOOL ret = FALSE;
196 if (priority == PRIORITY_NORMAL) {
197 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_NORMAL);
198 } else if (priority == PRIORITY_HIGH) {
199 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_HIGHEST);
200 } else if (priority == PRIORITY_ABOVE_NORMAL) {
201 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL);
202 } else if (priority == PRIORITY_IDLE) {
203 ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_IDLE);
204 }
205 if (!ret) {
206 return false;
207 }
208 }
209 priority_ = priority;
210 return true;
211#else
212 // TODO: Implement for Linux/Mac if possible.
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000213 if (running()) return false;
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000214 priority_ = priority;
215 return true;
216#endif
217}
218
219bool Thread::Start(Runnable* runnable) {
220 ASSERT(owned_);
221 if (!owned_) return false;
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000222 ASSERT(!running());
223 if (running()) return false;
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000224
225 Restart(); // reset fStop_ if the thread is being restarted
226
227 // Make sure that ThreadManager is created on the main thread before
228 // we start a new thread.
229 ThreadManager::Instance();
230
231 ThreadInit* init = new ThreadInit;
232 init->thread = this;
233 init->runnable = runnable;
234#if defined(WIN32)
235 DWORD flags = 0;
236 if (priority_ != PRIORITY_NORMAL) {
237 flags = CREATE_SUSPENDED;
238 }
239 thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PreRun, init, flags,
240 &thread_id_);
241 if (thread_) {
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000242 running_.Set();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000243 if (priority_ != PRIORITY_NORMAL) {
244 SetPriority(priority_);
245 ::ResumeThread(thread_);
246 }
247 } else {
248 return false;
249 }
250#elif defined(POSIX)
251 pthread_attr_t attr;
252 pthread_attr_init(&attr);
wu@webrtc.org2a81a382014-01-03 22:08:47 +0000253
254 // Thread priorities are not supported in NaCl.
255#if !defined(__native_client__)
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000256 if (priority_ != PRIORITY_NORMAL) {
257 if (priority_ == PRIORITY_IDLE) {
258 // There is no POSIX-standard way to set a below-normal priority for an
259 // individual thread (only whole process), so let's not support it.
260 LOG(LS_WARNING) << "PRIORITY_IDLE not supported";
261 } else {
262 // Set real-time round-robin policy.
263 if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0) {
264 LOG(LS_ERROR) << "pthread_attr_setschedpolicy";
265 }
266 struct sched_param param;
267 if (pthread_attr_getschedparam(&attr, &param) != 0) {
268 LOG(LS_ERROR) << "pthread_attr_getschedparam";
269 } else {
270 // The numbers here are arbitrary.
271 if (priority_ == PRIORITY_HIGH) {
272 param.sched_priority = 6; // 6 = HIGH
273 } else {
274 ASSERT(priority_ == PRIORITY_ABOVE_NORMAL);
275 param.sched_priority = 4; // 4 = ABOVE_NORMAL
276 }
277 if (pthread_attr_setschedparam(&attr, &param) != 0) {
278 LOG(LS_ERROR) << "pthread_attr_setschedparam";
279 }
280 }
281 }
282 }
wu@webrtc.org2a81a382014-01-03 22:08:47 +0000283#endif // !defined(__native_client__)
284
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000285 int error_code = pthread_create(&thread_, &attr, PreRun, init);
286 if (0 != error_code) {
287 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
288 return false;
289 }
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000290 running_.Set();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000291#endif
292 return true;
293}
294
295void Thread::Join() {
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000296 if (running()) {
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000297 ASSERT(!IsCurrent());
298#if defined(WIN32)
299 WaitForSingleObject(thread_, INFINITE);
300 CloseHandle(thread_);
301 thread_ = NULL;
302 thread_id_ = 0;
303#elif defined(POSIX)
304 void *pv;
305 pthread_join(thread_, &pv);
306#endif
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000307 running_.Reset();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000308 }
309}
310
311#ifdef WIN32
312// As seen on MSDN.
313// http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx
314#define MSDEV_SET_THREAD_NAME 0x406D1388
315typedef struct tagTHREADNAME_INFO {
316 DWORD dwType;
317 LPCSTR szName;
318 DWORD dwThreadID;
319 DWORD dwFlags;
320} THREADNAME_INFO;
321
322void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) {
323 THREADNAME_INFO info;
324 info.dwType = 0x1000;
325 info.szName = szThreadName;
326 info.dwThreadID = dwThreadID;
327 info.dwFlags = 0;
328
329 __try {
330 RaiseException(MSDEV_SET_THREAD_NAME, 0, sizeof(info) / sizeof(DWORD),
331 reinterpret_cast<ULONG_PTR*>(&info));
332 }
333 __except(EXCEPTION_CONTINUE_EXECUTION) {
334 }
335}
336#endif // WIN32
337
338void* Thread::PreRun(void* pv) {
339 ThreadInit* init = static_cast<ThreadInit*>(pv);
340 ThreadManager::Instance()->SetCurrentThread(init->thread);
341#if defined(WIN32)
342 SetThreadName(GetCurrentThreadId(), init->thread->name_.c_str());
343#elif defined(POSIX)
344 // TODO: See if naming exists for pthreads.
345#endif
346#if __has_feature(objc_arc)
347 @autoreleasepool
348#elif defined(OSX) || defined(IOS)
349 // Make sure the new thread has an autoreleasepool
350 ScopedAutoreleasePool pool;
351#endif
352 {
353 if (init->runnable) {
354 init->runnable->Run(init->thread);
355 } else {
356 init->thread->Run();
357 }
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000358 delete init;
359 return NULL;
360 }
361}
362
363void Thread::Run() {
364 ProcessMessages(kForever);
365}
366
367bool Thread::IsOwned() {
368 return owned_;
369}
370
371void Thread::Stop() {
372 MessageQueue::Quit();
373 Join();
374}
375
376void Thread::Send(MessageHandler *phandler, uint32 id, MessageData *pdata) {
377 if (fStop_)
378 return;
379
380 // Sent messages are sent to the MessageHandler directly, in the context
381 // of "thread", like Win32 SendMessage. If in the right context,
382 // call the handler directly.
383
384 Message msg;
385 msg.phandler = phandler;
386 msg.message_id = id;
387 msg.pdata = pdata;
388 if (IsCurrent()) {
389 phandler->OnMessage(&msg);
390 return;
391 }
392
393 AutoThread thread;
394 Thread *current_thread = Thread::Current();
395 ASSERT(current_thread != NULL); // AutoThread ensures this
396
397 bool ready = false;
398 {
399 CritScope cs(&crit_);
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000400 _SendMessage smsg;
401 smsg.thread = current_thread;
402 smsg.msg = msg;
403 smsg.ready = &ready;
404 sendlist_.push_back(smsg);
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000405 }
406
407 // Wait for a reply
408
409 ss_->WakeUp();
410
411 bool waited = false;
mallinath@webrtc.org8841d7b2013-10-13 17:18:27 +0000412 crit_.Enter();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000413 while (!ready) {
mallinath@webrtc.org8841d7b2013-10-13 17:18:27 +0000414 crit_.Leave();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000415 current_thread->ReceiveSends();
416 current_thread->socketserver()->Wait(kForever, false);
417 waited = true;
mallinath@webrtc.org8841d7b2013-10-13 17:18:27 +0000418 crit_.Enter();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000419 }
mallinath@webrtc.org8841d7b2013-10-13 17:18:27 +0000420 crit_.Leave();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000421
422 // Our Wait loop above may have consumed some WakeUp events for this
423 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
424 // cause problems for some SocketServers.
425 //
426 // Concrete example:
427 // Win32SocketServer on thread A calls Send on thread B. While processing the
428 // message, thread B Posts a message to A. We consume the wakeup for that
429 // Post while waiting for the Send to complete, which means that when we exit
430 // this loop, we need to issue another WakeUp, or else the Posted message
431 // won't be processed in a timely manner.
432
433 if (waited) {
434 current_thread->socketserver()->WakeUp();
435 }
436}
437
438void Thread::ReceiveSends() {
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000439 // Receive a sent message. Cleanup scenarios:
440 // - thread sending exits: We don't allow this, since thread can exit
441 // only via Join, so Send must complete.
442 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
443 // - object target cleared: Wakeup/set ready in Thread::Clear()
444 crit_.Enter();
445 while (!sendlist_.empty()) {
446 _SendMessage smsg = sendlist_.front();
447 sendlist_.pop_front();
448 crit_.Leave();
449 smsg.msg.phandler->OnMessage(&smsg.msg);
450 crit_.Enter();
451 *smsg.ready = true;
452 smsg.thread->socketserver()->WakeUp();
453 }
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000454 crit_.Leave();
455}
456
457void Thread::Clear(MessageHandler *phandler, uint32 id,
458 MessageList* removed) {
459 CritScope cs(&crit_);
460
461 // Remove messages on sendlist_ with phandler
462 // Object target cleared: remove from send list, wakeup/set ready
463 // if sender not NULL.
464
465 std::list<_SendMessage>::iterator iter = sendlist_.begin();
466 while (iter != sendlist_.end()) {
467 _SendMessage smsg = *iter;
468 if (smsg.msg.Match(phandler, id)) {
469 if (removed) {
470 removed->push_back(smsg.msg);
471 } else {
472 delete smsg.msg.pdata;
473 }
474 iter = sendlist_.erase(iter);
475 *smsg.ready = true;
476 smsg.thread->socketserver()->WakeUp();
477 continue;
478 }
479 ++iter;
480 }
481
482 MessageQueue::Clear(phandler, id, removed);
483}
484
485bool Thread::ProcessMessages(int cmsLoop) {
486 uint32 msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
487 int cmsNext = cmsLoop;
488
489 while (true) {
490#if __has_feature(objc_arc)
491 @autoreleasepool
492#elif defined(OSX) || defined(IOS)
493 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
494 // Each thread is supposed to have an autorelease pool. Also for event loops
495 // like this, autorelease pool needs to be created and drained/released
496 // for each cycle.
497 ScopedAutoreleasePool pool;
498#endif
499 {
500 Message msg;
501 if (!Get(&msg, cmsNext))
502 return !IsQuitting();
503 Dispatch(&msg);
504
505 if (cmsLoop != kForever) {
506 cmsNext = TimeUntil(msEnd);
507 if (cmsNext < 0)
508 return true;
509 }
510 }
511 }
512}
513
514bool Thread::WrapCurrent() {
515 return WrapCurrentWithThreadManager(ThreadManager::Instance());
516}
517
518bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager) {
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000519 if (running())
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000520 return false;
521#if defined(WIN32)
522 // We explicitly ask for no rights other than synchronization.
523 // This gives us the best chance of succeeding.
524 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
525 if (!thread_) {
526 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
527 return false;
528 }
529 thread_id_ = GetCurrentThreadId();
530#elif defined(POSIX)
531 thread_ = pthread_self();
532#endif
533 owned_ = false;
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000534 running_.Set();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000535 thread_manager->SetCurrentThread(this);
536 return true;
537}
538
539void Thread::UnwrapCurrent() {
540 // Clears the platform-specific thread-specific storage.
541 ThreadManager::Instance()->SetCurrentThread(NULL);
542#ifdef WIN32
543 if (!CloseHandle(thread_)) {
544 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
545 }
546#endif
fischman@webrtc.org738caf82014-05-23 17:28:50 +0000547 running_.Reset();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000548}
549
550
551AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
552 if (!ThreadManager::Instance()->CurrentThread()) {
553 ThreadManager::Instance()->SetCurrentThread(this);
554 }
555}
556
557AutoThread::~AutoThread() {
wu@webrtc.orge5b49102013-10-18 16:27:26 +0000558 Stop();
henrike@webrtc.org0e118e72013-07-10 00:45:36 +0000559 if (ThreadManager::Instance()->CurrentThread() == this) {
560 ThreadManager::Instance()->SetCurrentThread(NULL);
561 }
562}
563
564#ifdef WIN32
565void ComThread::Run() {
566 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
567 ASSERT(SUCCEEDED(hr));
568 if (SUCCEEDED(hr)) {
569 Thread::Run();
570 CoUninitialize();
571 } else {
572 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
573 }
574}
575#endif
576
577} // namespace talk_base