blob: dc8ccdfd4dd1dafd958f487450e254bb7b901693 [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"
Tommiea14f0a2015-05-18 13:51:06 +020025#include "webrtc/base/platform_thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026#include "webrtc/base/stringutils.h"
27#include "webrtc/base/timeutils.h"
28
29#if !__has_feature(objc_arc) && (defined(WEBRTC_MAC))
30#include "webrtc/base/maccocoathreadhelper.h"
31#include "webrtc/base/scoped_autorelease_pool.h"
32#endif
33
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000034#include "webrtc/base/trace_event.h"
35
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036namespace rtc {
37
38ThreadManager* ThreadManager::Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -070039 RTC_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040 return &thread_manager;
41}
42
43// static
44Thread* Thread::Current() {
45 return ThreadManager::Instance()->CurrentThread();
46}
47
48#if defined(WEBRTC_POSIX)
49ThreadManager::ThreadManager() {
50 pthread_key_create(&key_, NULL);
51#ifndef NO_MAIN_THREAD_WRAPPING
52 WrapCurrentThread();
53#endif
54#if !__has_feature(objc_arc) && (defined(WEBRTC_MAC))
55 // Under Automatic Reference Counting (ARC), you cannot use autorelease pools
56 // directly. Instead, you use @autoreleasepool blocks instead. Also, we are
57 // maintaining thread safety using immutability within context of GCD dispatch
58 // queues in this case.
59 InitCocoaMultiThreading();
60#endif
61}
62
63ThreadManager::~ThreadManager() {
64#if __has_feature(objc_arc)
65 @autoreleasepool
66#elif defined(WEBRTC_MAC)
67 // This is called during exit, at which point apparently no NSAutoreleasePools
68 // are available; but we might still need them to do cleanup (or we get the
69 // "no autoreleasepool in place, just leaking" warning when exiting).
70 ScopedAutoreleasePool pool;
71#endif
72 {
73 UnwrapCurrentThread();
74 pthread_key_delete(key_);
75 }
76}
77
78Thread *ThreadManager::CurrentThread() {
79 return static_cast<Thread *>(pthread_getspecific(key_));
80}
81
82void ThreadManager::SetCurrentThread(Thread *thread) {
83 pthread_setspecific(key_, thread);
84}
85#endif
86
87#if defined(WEBRTC_WIN)
88ThreadManager::ThreadManager() {
89 key_ = TlsAlloc();
90#ifndef NO_MAIN_THREAD_WRAPPING
91 WrapCurrentThread();
92#endif
93}
94
95ThreadManager::~ThreadManager() {
96 UnwrapCurrentThread();
97 TlsFree(key_);
98}
99
100Thread *ThreadManager::CurrentThread() {
101 return static_cast<Thread *>(TlsGetValue(key_));
102}
103
104void ThreadManager::SetCurrentThread(Thread *thread) {
105 TlsSetValue(key_, thread);
106}
107#endif
108
109Thread *ThreadManager::WrapCurrentThread() {
110 Thread* result = CurrentThread();
111 if (NULL == result) {
112 result = new Thread();
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000113 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000114 }
115 return result;
116}
117
118void ThreadManager::UnwrapCurrentThread() {
119 Thread* t = CurrentThread();
120 if (t && !(t->IsOwned())) {
121 t->UnwrapCurrent();
122 delete t;
123 }
124}
125
126struct ThreadInit {
127 Thread* thread;
128 Runnable* runnable;
129};
130
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000131Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
132 : thread_(Thread::Current()),
133 previous_state_(thread_->SetAllowBlockingCalls(false)) {
134}
135
136Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
137 ASSERT(thread_->IsCurrent());
138 thread_->SetAllowBlockingCalls(previous_state_);
139}
140
jbauch25d1f282016-02-05 00:25:02 -0800141Thread::Thread(SocketServer* ss, bool init_queue)
142 : MessageQueue(ss, false),
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000143 running_(true, false),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144#if defined(WEBRTC_WIN)
145 thread_(NULL),
146 thread_id_(0),
147#endif
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000148 owned_(true),
149 blocking_calls_allowed_(true) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000150 SetName("Thread", this); // default name
jbauch25d1f282016-02-05 00:25:02 -0800151 if (init_queue) {
152 DoInit();
153 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000154}
155
156Thread::~Thread() {
157 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800158 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000159}
160
161bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000162 AssertBlockingIsAllowedOnCurrentThread();
163
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164#if defined(WEBRTC_WIN)
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) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000183 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184 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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000193bool Thread::Start(Runnable* runnable) {
194 ASSERT(owned_);
195 if (!owned_) return false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000196 ASSERT(!running());
197 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198
199 Restart(); // reset fStop_ if the thread is being restarted
200
201 // Make sure that ThreadManager is created on the main thread before
202 // we start a new thread.
203 ThreadManager::Instance();
204
205 ThreadInit* init = new ThreadInit;
206 init->thread = this;
207 init->runnable = runnable;
208#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100209 thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PreRun, init, 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210 &thread_id_);
211 if (thread_) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000212 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213 } else {
214 return false;
215 }
216#elif defined(WEBRTC_POSIX)
217 pthread_attr_t attr;
218 pthread_attr_init(&attr);
219
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220 int error_code = pthread_create(&thread_, &attr, PreRun, init);
221 if (0 != error_code) {
222 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
223 return false;
224 }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000225 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226#endif
227 return true;
228}
229
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000230bool Thread::WrapCurrent() {
231 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
232}
233
234void Thread::UnwrapCurrent() {
235 // Clears the platform-specific thread-specific storage.
236 ThreadManager::Instance()->SetCurrentThread(NULL);
237#if defined(WEBRTC_WIN)
238 if (thread_ != NULL) {
239 if (!CloseHandle(thread_)) {
240 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
241 }
242 thread_ = NULL;
243 }
244#endif
245 running_.Reset();
246}
247
248void Thread::SafeWrapCurrent() {
249 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
250}
251
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252void Thread::Join() {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000253 if (running()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254 ASSERT(!IsCurrent());
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000255 if (Current() && !Current()->blocking_calls_allowed_) {
256 LOG(LS_WARNING) << "Waiting for the thread to join, "
257 << "but blocking calls have been disallowed";
258 }
259
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000261 ASSERT(thread_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 WaitForSingleObject(thread_, INFINITE);
263 CloseHandle(thread_);
264 thread_ = NULL;
265 thread_id_ = 0;
266#elif defined(WEBRTC_POSIX)
267 void *pv;
268 pthread_join(thread_, &pv);
269#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000270 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271 }
272}
273
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000274bool Thread::SetAllowBlockingCalls(bool allow) {
275 ASSERT(IsCurrent());
276 bool previous = blocking_calls_allowed_;
277 blocking_calls_allowed_ = allow;
278 return previous;
279}
280
281// static
282void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700283#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000284 Thread* current = Thread::Current();
285 ASSERT(!current || current->blocking_calls_allowed_);
286#endif
287}
288
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000289void* Thread::PreRun(void* pv) {
290 ThreadInit* init = static_cast<ThreadInit*>(pv);
291 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200292 rtc::SetCurrentThreadName(init->thread->name_.c_str());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293#if __has_feature(objc_arc)
294 @autoreleasepool
295#elif defined(WEBRTC_MAC)
296 // Make sure the new thread has an autoreleasepool
297 ScopedAutoreleasePool pool;
298#endif
299 {
300 if (init->runnable) {
301 init->runnable->Run(init->thread);
302 } else {
303 init->thread->Run();
304 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000305 delete init;
306 return NULL;
307 }
308}
309
310void Thread::Run() {
311 ProcessMessages(kForever);
312}
313
314bool Thread::IsOwned() {
315 return owned_;
316}
317
318void Thread::Stop() {
319 MessageQueue::Quit();
320 Join();
321}
322
Peter Boström0c4e06b2015-10-07 12:23:21 +0200323void Thread::Send(MessageHandler* phandler, uint32_t id, MessageData* pdata) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324 if (fStop_)
325 return;
326
327 // Sent messages are sent to the MessageHandler directly, in the context
328 // of "thread", like Win32 SendMessage. If in the right context,
329 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330 Message msg;
331 msg.phandler = phandler;
332 msg.message_id = id;
333 msg.pdata = pdata;
334 if (IsCurrent()) {
335 phandler->OnMessage(&msg);
336 return;
337 }
338
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000339 AssertBlockingIsAllowedOnCurrentThread();
340
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341 AutoThread thread;
342 Thread *current_thread = Thread::Current();
343 ASSERT(current_thread != NULL); // AutoThread ensures this
344
345 bool ready = false;
346 {
347 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348 _SendMessage smsg;
349 smsg.thread = current_thread;
350 smsg.msg = msg;
351 smsg.ready = &ready;
352 sendlist_.push_back(smsg);
353 }
354
355 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800356 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000357
358 bool waited = false;
359 crit_.Enter();
360 while (!ready) {
361 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000362 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
363 // thread invoking calls on the current thread.
364 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000365 current_thread->socketserver()->Wait(kForever, false);
366 waited = true;
367 crit_.Enter();
368 }
369 crit_.Leave();
370
371 // Our Wait loop above may have consumed some WakeUp events for this
372 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
373 // cause problems for some SocketServers.
374 //
375 // Concrete example:
376 // Win32SocketServer on thread A calls Send on thread B. While processing the
377 // message, thread B Posts a message to A. We consume the wakeup for that
378 // Post while waiting for the Send to complete, which means that when we exit
379 // this loop, we need to issue another WakeUp, or else the Posted message
380 // won't be processed in a timely manner.
381
382 if (waited) {
383 current_thread->socketserver()->WakeUp();
384 }
385}
386
387void Thread::ReceiveSends() {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000388 ReceiveSendsFromThread(NULL);
389}
390
391void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000392 // Receive a sent message. Cleanup scenarios:
393 // - thread sending exits: We don't allow this, since thread can exit
394 // only via Join, so Send must complete.
395 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
396 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000397 _SendMessage smsg;
398
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000399 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000400 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000401 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000402
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000403 smsg.msg.phandler->OnMessage(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000404
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000405 crit_.Enter();
406 *smsg.ready = true;
407 smsg.thread->socketserver()->WakeUp();
408 }
409 crit_.Leave();
410}
411
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000412bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
413 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
414 it != sendlist_.end(); ++it) {
415 if (it->thread == source || source == NULL) {
416 *msg = *it;
417 sendlist_.erase(it);
418 return true;
419 }
420 }
421 return false;
422}
423
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000424void Thread::InvokeBegin() {
425 TRACE_EVENT_BEGIN0("webrtc", "Thread::Invoke");
426}
427
428void Thread::InvokeEnd() {
429 TRACE_EVENT_END0("webrtc", "Thread::Invoke");
430}
431
Peter Boström0c4e06b2015-10-07 12:23:21 +0200432void Thread::Clear(MessageHandler* phandler,
433 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000434 MessageList* removed) {
435 CritScope cs(&crit_);
436
437 // Remove messages on sendlist_ with phandler
438 // Object target cleared: remove from send list, wakeup/set ready
439 // if sender not NULL.
440
441 std::list<_SendMessage>::iterator iter = sendlist_.begin();
442 while (iter != sendlist_.end()) {
443 _SendMessage smsg = *iter;
444 if (smsg.msg.Match(phandler, id)) {
445 if (removed) {
446 removed->push_back(smsg.msg);
447 } else {
448 delete smsg.msg.pdata;
449 }
450 iter = sendlist_.erase(iter);
451 *smsg.ready = true;
452 smsg.thread->socketserver()->WakeUp();
453 continue;
454 }
455 ++iter;
456 }
457
458 MessageQueue::Clear(phandler, id, removed);
459}
460
461bool Thread::ProcessMessages(int cmsLoop) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200462 uint32_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000463 int cmsNext = cmsLoop;
464
465 while (true) {
466#if __has_feature(objc_arc)
467 @autoreleasepool
468#elif defined(WEBRTC_MAC)
469 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
470 // Each thread is supposed to have an autorelease pool. Also for event loops
471 // like this, autorelease pool needs to be created and drained/released
472 // for each cycle.
473 ScopedAutoreleasePool pool;
474#endif
475 {
476 Message msg;
477 if (!Get(&msg, cmsNext))
478 return !IsQuitting();
479 Dispatch(&msg);
480
481 if (cmsLoop != kForever) {
482 cmsNext = TimeUntil(msEnd);
483 if (cmsNext < 0)
484 return true;
485 }
486 }
487 }
488}
489
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000490bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
491 bool need_synchronize_access) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000492 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000493 return false;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000494
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000495#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000496 if (need_synchronize_access) {
497 // We explicitly ask for no rights other than synchronization.
498 // This gives us the best chance of succeeding.
499 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
500 if (!thread_) {
501 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
502 return false;
503 }
504 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000505 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000506#elif defined(WEBRTC_POSIX)
507 thread_ = pthread_self();
508#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000509
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000511 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512 thread_manager->SetCurrentThread(this);
513 return true;
514}
515
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000516AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
517 if (!ThreadManager::Instance()->CurrentThread()) {
518 ThreadManager::Instance()->SetCurrentThread(this);
519 }
520}
521
522AutoThread::~AutoThread() {
523 Stop();
524 if (ThreadManager::Instance()->CurrentThread() == this) {
525 ThreadManager::Instance()->SetCurrentThread(NULL);
526 }
527}
528
529#if defined(WEBRTC_WIN)
530void ComThread::Run() {
531 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
532 ASSERT(SUCCEEDED(hr));
533 if (SUCCEEDED(hr)) {
534 Thread::Run();
535 CoUninitialize();
536 } else {
537 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
538 }
539}
540#endif
541
542} // namespace rtc