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