1 /*
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
50 namespace talk_base {
51
Instance()52 ThreadManager* ThreadManager::Instance() {
53 LIBJINGLE_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
54 return &thread_manager;
55 }
56
57 // static
Current()58 Thread* Thread::Current() {
59 return ThreadManager::Instance()->CurrentThread();
60 }
61
62 #ifdef POSIX
ThreadManager()63 ThreadManager::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
~ThreadManager()77 ThreadManager::~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
CurrentThread()92 Thread *ThreadManager::CurrentThread() {
93 return static_cast<Thread *>(pthread_getspecific(key_));
94 }
95
SetCurrentThread(Thread * thread)96 void ThreadManager::SetCurrentThread(Thread *thread) {
97 pthread_setspecific(key_, thread);
98 }
99 #endif
100
101 #ifdef WIN32
ThreadManager()102 ThreadManager::ThreadManager() {
103 key_ = TlsAlloc();
104 #ifndef NO_MAIN_THREAD_WRAPPING
105 WrapCurrentThread();
106 #endif
107 }
108
~ThreadManager()109 ThreadManager::~ThreadManager() {
110 UnwrapCurrentThread();
111 TlsFree(key_);
112 }
113
CurrentThread()114 Thread *ThreadManager::CurrentThread() {
115 return static_cast<Thread *>(TlsGetValue(key_));
116 }
117
SetCurrentThread(Thread * thread)118 void ThreadManager::SetCurrentThread(Thread *thread) {
119 TlsSetValue(key_, thread);
120 }
121 #endif
122
WrapCurrentThread()123 Thread *ThreadManager::WrapCurrentThread() {
124 Thread* result = CurrentThread();
125 if (NULL == result) {
126 result = new Thread();
127 result->WrapCurrentWithThreadManager(this);
128 }
129 return result;
130 }
131
UnwrapCurrentThread()132 void ThreadManager::UnwrapCurrentThread() {
133 Thread* t = CurrentThread();
134 if (t && !(t->IsOwned())) {
135 t->UnwrapCurrent();
136 delete t;
137 }
138 }
139
140 struct ThreadInit {
141 Thread* thread;
142 Runnable* runnable;
143 };
144
Thread(SocketServer * ss)145 Thread::Thread(SocketServer* ss)
146 : MessageQueue(ss),
147 priority_(PRIORITY_NORMAL),
148 running_(true, false),
149 #if defined(WIN32)
150 thread_(NULL),
151 thread_id_(0),
152 #endif
153 owned_(true) {
154 SetName("Thread", this); // default name
155 }
156
~Thread()157 Thread::~Thread() {
158 Stop();
159 Clear(NULL);
160 }
161
SleepMs(int milliseconds)162 bool 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
SetName(const std::string & name,const void * obj)181 bool Thread::SetName(const std::string& name, const void* obj) {
182 if (running()) return false;
183 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
SetPriority(ThreadPriority priority)192 bool Thread::SetPriority(ThreadPriority priority) {
193 #if defined(WIN32)
194 if (running()) {
195 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.
213 if (running()) return false;
214 priority_ = priority;
215 return true;
216 #endif
217 }
218
Start(Runnable * runnable)219 bool Thread::Start(Runnable* runnable) {
220 ASSERT(owned_);
221 if (!owned_) return false;
222 ASSERT(!running());
223 if (running()) return false;
224
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_) {
242 running_.Set();
243 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);
253
254 // Thread priorities are not supported in NaCl.
255 #if !defined(__native_client__)
256 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, ¶m) != 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, ¶m) != 0) {
278 LOG(LS_ERROR) << "pthread_attr_setschedparam";
279 }
280 }
281 }
282 }
283 #endif // !defined(__native_client__)
284
285 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 }
290 running_.Set();
291 #endif
292 return true;
293 }
294
Join()295 void Thread::Join() {
296 if (running()) {
297 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
307 running_.Reset();
308 }
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
315 typedef struct tagTHREADNAME_INFO {
316 DWORD dwType;
317 LPCSTR szName;
318 DWORD dwThreadID;
319 DWORD dwFlags;
320 } THREADNAME_INFO;
321
SetThreadName(DWORD dwThreadID,LPCSTR szThreadName)322 void 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
PreRun(void * pv)338 void* 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 }
358 delete init;
359 return NULL;
360 }
361 }
362
Run()363 void Thread::Run() {
364 ProcessMessages(kForever);
365 }
366
IsOwned()367 bool Thread::IsOwned() {
368 return owned_;
369 }
370
Stop()371 void Thread::Stop() {
372 MessageQueue::Quit();
373 Join();
374 }
375
Send(MessageHandler * phandler,uint32 id,MessageData * pdata)376 void 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_);
400 _SendMessage smsg;
401 smsg.thread = current_thread;
402 smsg.msg = msg;
403 smsg.ready = &ready;
404 sendlist_.push_back(smsg);
405 }
406
407 // Wait for a reply
408
409 ss_->WakeUp();
410
411 bool waited = false;
412 crit_.Enter();
413 while (!ready) {
414 crit_.Leave();
415 current_thread->ReceiveSends();
416 current_thread->socketserver()->Wait(kForever, false);
417 waited = true;
418 crit_.Enter();
419 }
420 crit_.Leave();
421
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
ReceiveSends()438 void Thread::ReceiveSends() {
439 // 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 }
454 crit_.Leave();
455 }
456
Clear(MessageHandler * phandler,uint32 id,MessageList * removed)457 void 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
ProcessMessages(int cmsLoop)485 bool 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
WrapCurrent()514 bool Thread::WrapCurrent() {
515 return WrapCurrentWithThreadManager(ThreadManager::Instance());
516 }
517
WrapCurrentWithThreadManager(ThreadManager * thread_manager)518 bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager) {
519 if (running())
520 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;
534 running_.Set();
535 thread_manager->SetCurrentThread(this);
536 return true;
537 }
538
UnwrapCurrent()539 void 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
547 running_.Reset();
548 }
549
550
AutoThread(SocketServer * ss)551 AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
552 if (!ThreadManager::Instance()->CurrentThread()) {
553 ThreadManager::Instance()->SetCurrentThread(this);
554 }
555 }
556
~AutoThread()557 AutoThread::~AutoThread() {
558 Stop();
559 if (ThreadManager::Instance()->CurrentThread() == this) {
560 ThreadManager::Instance()->SetCurrentThread(NULL);
561 }
562 }
563
564 #ifdef WIN32
Run()565 void 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
578