blob: cda4ba475c8b6bfebd80fe994c518f4b55d3e666 [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
356
357 ss_->WakeUp();
358
359 bool waited = false;
360 crit_.Enter();
361 while (!ready) {
362 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000363 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
364 // thread invoking calls on the current thread.
365 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000366 current_thread->socketserver()->Wait(kForever, false);
367 waited = true;
368 crit_.Enter();
369 }
370 crit_.Leave();
371
372 // Our Wait loop above may have consumed some WakeUp events for this
373 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
374 // cause problems for some SocketServers.
375 //
376 // Concrete example:
377 // Win32SocketServer on thread A calls Send on thread B. While processing the
378 // message, thread B Posts a message to A. We consume the wakeup for that
379 // Post while waiting for the Send to complete, which means that when we exit
380 // this loop, we need to issue another WakeUp, or else the Posted message
381 // won't be processed in a timely manner.
382
383 if (waited) {
384 current_thread->socketserver()->WakeUp();
385 }
386}
387
388void Thread::ReceiveSends() {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000389 ReceiveSendsFromThread(NULL);
390}
391
392void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000393 // Receive a sent message. Cleanup scenarios:
394 // - thread sending exits: We don't allow this, since thread can exit
395 // only via Join, so Send must complete.
396 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
397 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000398 _SendMessage smsg;
399
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000400 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000401 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000402 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000403
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000404 smsg.msg.phandler->OnMessage(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000405
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000406 crit_.Enter();
407 *smsg.ready = true;
408 smsg.thread->socketserver()->WakeUp();
409 }
410 crit_.Leave();
411}
412
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000413bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
414 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
415 it != sendlist_.end(); ++it) {
416 if (it->thread == source || source == NULL) {
417 *msg = *it;
418 sendlist_.erase(it);
419 return true;
420 }
421 }
422 return false;
423}
424
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000425void Thread::InvokeBegin() {
426 TRACE_EVENT_BEGIN0("webrtc", "Thread::Invoke");
427}
428
429void Thread::InvokeEnd() {
430 TRACE_EVENT_END0("webrtc", "Thread::Invoke");
431}
432
Peter Boström0c4e06b2015-10-07 12:23:21 +0200433void Thread::Clear(MessageHandler* phandler,
434 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000435 MessageList* removed) {
436 CritScope cs(&crit_);
437
438 // Remove messages on sendlist_ with phandler
439 // Object target cleared: remove from send list, wakeup/set ready
440 // if sender not NULL.
441
442 std::list<_SendMessage>::iterator iter = sendlist_.begin();
443 while (iter != sendlist_.end()) {
444 _SendMessage smsg = *iter;
445 if (smsg.msg.Match(phandler, id)) {
446 if (removed) {
447 removed->push_back(smsg.msg);
448 } else {
449 delete smsg.msg.pdata;
450 }
451 iter = sendlist_.erase(iter);
452 *smsg.ready = true;
453 smsg.thread->socketserver()->WakeUp();
454 continue;
455 }
456 ++iter;
457 }
458
459 MessageQueue::Clear(phandler, id, removed);
460}
461
462bool Thread::ProcessMessages(int cmsLoop) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200463 uint32_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000464 int cmsNext = cmsLoop;
465
466 while (true) {
467#if __has_feature(objc_arc)
468 @autoreleasepool
469#elif defined(WEBRTC_MAC)
470 // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
471 // Each thread is supposed to have an autorelease pool. Also for event loops
472 // like this, autorelease pool needs to be created and drained/released
473 // for each cycle.
474 ScopedAutoreleasePool pool;
475#endif
476 {
477 Message msg;
478 if (!Get(&msg, cmsNext))
479 return !IsQuitting();
480 Dispatch(&msg);
481
482 if (cmsLoop != kForever) {
483 cmsNext = TimeUntil(msEnd);
484 if (cmsNext < 0)
485 return true;
486 }
487 }
488 }
489}
490
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000491bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
492 bool need_synchronize_access) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000493 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000494 return false;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000495
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000496#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000497 if (need_synchronize_access) {
498 // We explicitly ask for no rights other than synchronization.
499 // This gives us the best chance of succeeding.
500 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
501 if (!thread_) {
502 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
503 return false;
504 }
505 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000506 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000507#elif defined(WEBRTC_POSIX)
508 thread_ = pthread_self();
509#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000510
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000511 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000512 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000513 thread_manager->SetCurrentThread(this);
514 return true;
515}
516
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000517AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
518 if (!ThreadManager::Instance()->CurrentThread()) {
519 ThreadManager::Instance()->SetCurrentThread(this);
520 }
521}
522
523AutoThread::~AutoThread() {
524 Stop();
525 if (ThreadManager::Instance()->CurrentThread() == this) {
526 ThreadManager::Instance()->SetCurrentThread(NULL);
527 }
528}
529
530#if defined(WEBRTC_WIN)
531void ComThread::Run() {
532 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
533 ASSERT(SUCCEEDED(hr));
534 if (SUCCEEDED(hr)) {
535 Thread::Run();
536 CoUninitialize();
537 } else {
538 LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
539 }
540}
541#endif
542
543} // namespace rtc