blob: 0d1003ea78d18f4f84290aa25172ab2747c2c847 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013#if defined(WEBRTC_WIN)
14#include <comdef.h>
15#elif defined(WEBRTC_POSIX)
16#include <time.h>
Tommi51492422017-12-04 15:18:23 +010017#else
18#error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#endif
20
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/checks.h"
22#include "rtc_base/logging.h"
23#include "rtc_base/nullsocketserver.h"
24#include "rtc_base/platform_thread.h"
25#include "rtc_base/stringutils.h"
26#include "rtc_base/timeutils.h"
27#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029namespace rtc {
30
31ThreadManager* ThreadManager::Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -070032 RTC_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000033 return &thread_manager;
34}
35
nisse7866cfe2017-04-26 01:45:31 -070036ThreadManager::~ThreadManager() {
37 // By above RTC_DEFINE_STATIC_LOCAL.
38 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
39}
40
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041// static
42Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -070043 ThreadManager* manager = ThreadManager::Instance();
44 Thread* thread = manager->CurrentThread();
45
46#ifndef NO_MAIN_THREAD_WRAPPING
47 // Only autowrap the thread which instantiated the ThreadManager.
48 if (!thread && manager->IsMainThread()) {
tommie7251592017-07-14 14:44:46 -070049 thread = new Thread(SocketServer::CreateDefault());
nisse7866cfe2017-04-26 01:45:31 -070050 thread->WrapCurrentWithThreadManager(manager, true);
51 }
52#endif
53
54 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055}
56
57#if defined(WEBRTC_POSIX)
kthelgason61abe152017-03-29 02:32:36 -070058#if !defined(WEBRTC_MAC)
Tommi51492422017-12-04 15:18:23 +010059ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
deadbeef37f5ecf2017-02-27 14:06:41 -080060 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000061}
kthelgason61abe152017-03-29 02:32:36 -070062#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063
64Thread *ThreadManager::CurrentThread() {
65 return static_cast<Thread *>(pthread_getspecific(key_));
66}
67
68void ThreadManager::SetCurrentThread(Thread *thread) {
Tommi51492422017-12-04 15:18:23 +010069 RTC_DCHECK(!CurrentThread() || !thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070 pthread_setspecific(key_, thread);
71}
72#endif
73
74#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +010075ThreadManager::ThreadManager()
76 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000077}
78
79Thread *ThreadManager::CurrentThread() {
80 return static_cast<Thread *>(TlsGetValue(key_));
81}
82
83void ThreadManager::SetCurrentThread(Thread *thread) {
Tommi51492422017-12-04 15:18:23 +010084 RTC_DCHECK(!CurrentThread() || !thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085 TlsSetValue(key_, thread);
86}
87#endif
88
89Thread *ThreadManager::WrapCurrentThread() {
90 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -080091 if (nullptr == result) {
tommie7251592017-07-14 14:44:46 -070092 result = new Thread(SocketServer::CreateDefault());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +000093 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094 }
95 return result;
96}
97
98void ThreadManager::UnwrapCurrentThread() {
99 Thread* t = CurrentThread();
100 if (t && !(t->IsOwned())) {
101 t->UnwrapCurrent();
102 delete t;
103 }
104}
105
nisse7866cfe2017-04-26 01:45:31 -0700106bool ThreadManager::IsMainThread() {
107 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
108}
109
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000110Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
111 : thread_(Thread::Current()),
112 previous_state_(thread_->SetAllowBlockingCalls(false)) {
113}
114
115Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800116 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000117 thread_->SetAllowBlockingCalls(previous_state_);
118}
119
tommie7251592017-07-14 14:44:46 -0700120// DEPRECATED.
danilchapbebf54c2016-04-28 01:32:48 -0700121Thread::Thread() : Thread(SocketServer::CreateDefault()) {}
122
Tommi51492422017-12-04 15:18:23 +0100123Thread::Thread(SocketServer* ss) : MessageQueue(ss, false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124 SetName("Thread", this); // default name
danilchapbebf54c2016-04-28 01:32:48 -0700125 DoInit();
126}
127
128Thread::Thread(std::unique_ptr<SocketServer> ss)
Tommi51492422017-12-04 15:18:23 +0100129 : MessageQueue(std::move(ss), false) {
danilchapbebf54c2016-04-28 01:32:48 -0700130 SetName("Thread", this); // default name
131 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000132}
133
134Thread::~Thread() {
135 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800136 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137}
138
nisse7866cfe2017-04-26 01:45:31 -0700139bool Thread::IsCurrent() const {
140 return ThreadManager::Instance()->CurrentThread() == this;
141}
142
danilchapbebf54c2016-04-28 01:32:48 -0700143std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
144 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
145}
146
147std::unique_ptr<Thread> Thread::Create() {
148 return std::unique_ptr<Thread>(
149 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
150}
151
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000153 AssertBlockingIsAllowedOnCurrentThread();
154
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000155#if defined(WEBRTC_WIN)
156 ::Sleep(milliseconds);
157 return true;
158#else
159 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
160 // so we use nanosleep() even though it has greater precision than necessary.
161 struct timespec ts;
162 ts.tv_sec = milliseconds / 1000;
163 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800164 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100166 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 return false;
168 }
169 return true;
170#endif
171}
172
173bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100174 RTC_DCHECK(!IsRunning());
175
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000176 name_ = name;
177 if (obj) {
178 char buf[16];
179 sprintfn(buf, sizeof(buf), " 0x%p", obj);
180 name_ += buf;
181 }
182 return true;
183}
184
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185bool Thread::Start(Runnable* runnable) {
Tommi51492422017-12-04 15:18:23 +0100186 RTC_DCHECK_RUN_ON(&thread_checker_);
187 RTC_DCHECK(!IsRunning());
188
189 if (IsRunning())
190 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000191
André Susano Pinto02a57972016-07-22 13:30:05 +0200192 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000193
194 // Make sure that ThreadManager is created on the main thread before
195 // we start a new thread.
196 ThreadManager::Instance();
197
Tommi51492422017-12-04 15:18:23 +0100198 owned_ = true;
199
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200 ThreadInit* init = new ThreadInit;
201 init->thread = this;
202 init->runnable = runnable;
203#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800204 thread_ = CreateThread(nullptr, 0, PreRun, init, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100205 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000206 return false;
207 }
208#elif defined(WEBRTC_POSIX)
209 pthread_attr_t attr;
210 pthread_attr_init(&attr);
211
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000212 int error_code = pthread_create(&thread_, &attr, PreRun, init);
213 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100214 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100215 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216 return false;
217 }
Tommi51492422017-12-04 15:18:23 +0100218 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000219#endif
220 return true;
221}
222
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000223bool Thread::WrapCurrent() {
224 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
225}
226
227void Thread::UnwrapCurrent() {
Tommi51492422017-12-04 15:18:23 +0100228 RTC_DCHECK_RUN_ON(&thread_checker_);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000229 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800230 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000231#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800232 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000233 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100234 RTC_LOG_GLE(LS_ERROR)
235 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000236 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800237 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100238 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000239 }
Tommi51492422017-12-04 15:18:23 +0100240#elif defined(WEBRTC_POSIX)
241 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000242#endif
Tommi51492422017-12-04 15:18:23 +0100243 thread_checker_.DetachFromThread();
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000244}
245
246void Thread::SafeWrapCurrent() {
247 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
248}
249
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100251 RTC_DCHECK_RUN_ON(&thread_checker_);
252 if (!IsRunning())
253 return;
254
255 RTC_DCHECK(!IsCurrent());
256 if (Current() && !Current()->blocking_calls_allowed_) {
257 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
258 << "but blocking calls have been disallowed";
259 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000260
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100262 RTC_DCHECK(thread_ != nullptr);
263 WaitForSingleObject(thread_, INFINITE);
264 CloseHandle(thread_);
265 thread_ = nullptr;
266 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100268 pthread_join(thread_, nullptr);
269 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270#endif
Tommi51492422017-12-04 15:18:23 +0100271 thread_checker_.DetachFromThread();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272}
273
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000274bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800275 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000276 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();
nisseede5da42017-01-12 05:15:36 -0800285 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000286#endif
287}
288
deadbeefdc20e262017-01-31 15:10:44 -0800289// static
kthelgason61abe152017-03-29 02:32:36 -0700290#if !defined(WEBRTC_MAC)
deadbeefdc20e262017-01-31 15:10:44 -0800291#if defined(WEBRTC_WIN)
292DWORD WINAPI Thread::PreRun(LPVOID pv) {
293#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000294void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800295#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000296 ThreadInit* init = static_cast<ThreadInit*>(pv);
297 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200298 rtc::SetCurrentThreadName(init->thread->name_.c_str());
kthelgasonde6adbe2017-02-22 00:42:11 -0800299 if (init->runnable) {
300 init->runnable->Run(init->thread);
301 } else {
302 init->thread->Run();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000303 }
Tommi51492422017-12-04 15:18:23 +0100304 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800305 delete init;
306#ifdef WEBRTC_WIN
307 return 0;
308#else
309 return nullptr;
310#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311}
kthelgason61abe152017-03-29 02:32:36 -0700312#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313
314void Thread::Run() {
315 ProcessMessages(kForever);
316}
317
318bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100319 RTC_DCHECK_RUN_ON(&thread_checker_);
320 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321 return owned_;
322}
323
324void Thread::Stop() {
Tommi51492422017-12-04 15:18:23 +0100325 RTC_DCHECK_RUN_ON(&thread_checker_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326 MessageQueue::Quit();
327 Join();
Tommi51492422017-12-04 15:18:23 +0100328 thread_checker_.DetachFromThread();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000329}
330
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700331void Thread::Send(const Location& posted_from,
332 MessageHandler* phandler,
333 uint32_t id,
334 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200335 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000336 return;
337
338 // Sent messages are sent to the MessageHandler directly, in the context
339 // of "thread", like Win32 SendMessage. If in the right context,
340 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700342 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000343 msg.phandler = phandler;
344 msg.message_id = id;
345 msg.pdata = pdata;
346 if (IsCurrent()) {
347 phandler->OnMessage(&msg);
348 return;
349 }
350
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000351 AssertBlockingIsAllowedOnCurrentThread();
352
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000353 AutoThread thread;
354 Thread *current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800355 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000356
357 bool ready = false;
358 {
359 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000360 _SendMessage smsg;
361 smsg.thread = current_thread;
362 smsg.msg = msg;
363 smsg.ready = &ready;
364 sendlist_.push_back(smsg);
365 }
366
367 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800368 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000369
370 bool waited = false;
371 crit_.Enter();
372 while (!ready) {
373 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000374 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
375 // thread invoking calls on the current thread.
376 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000377 current_thread->socketserver()->Wait(kForever, false);
378 waited = true;
379 crit_.Enter();
380 }
381 crit_.Leave();
382
383 // Our Wait loop above may have consumed some WakeUp events for this
384 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
385 // cause problems for some SocketServers.
386 //
387 // Concrete example:
388 // Win32SocketServer on thread A calls Send on thread B. While processing the
389 // message, thread B Posts a message to A. We consume the wakeup for that
390 // Post while waiting for the Send to complete, which means that when we exit
391 // this loop, we need to issue another WakeUp, or else the Posted message
392 // won't be processed in a timely manner.
393
394 if (waited) {
395 current_thread->socketserver()->WakeUp();
396 }
397}
398
399void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800400 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000401}
402
403void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000404 // Receive a sent message. Cleanup scenarios:
405 // - thread sending exits: We don't allow this, since thread can exit
406 // only via Join, so Send must complete.
407 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
408 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000409 _SendMessage smsg;
410
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000411 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000412 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000413 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000414
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000415 smsg.msg.phandler->OnMessage(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000416
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000417 crit_.Enter();
418 *smsg.ready = true;
419 smsg.thread->socketserver()->WakeUp();
420 }
421 crit_.Leave();
422}
423
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000424bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
425 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
426 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800427 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000428 *msg = *it;
429 sendlist_.erase(it);
430 return true;
431 }
432 }
433 return false;
434}
435
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700436void Thread::InvokeInternal(const Location& posted_from,
437 MessageHandler* handler) {
438 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
439 posted_from.file_and_line(), "src_func",
440 posted_from.function_name());
441 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000442}
443
Peter Boström0c4e06b2015-10-07 12:23:21 +0200444void Thread::Clear(MessageHandler* phandler,
445 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000446 MessageList* removed) {
447 CritScope cs(&crit_);
448
449 // Remove messages on sendlist_ with phandler
450 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800451 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000452
453 std::list<_SendMessage>::iterator iter = sendlist_.begin();
454 while (iter != sendlist_.end()) {
455 _SendMessage smsg = *iter;
456 if (smsg.msg.Match(phandler, id)) {
457 if (removed) {
458 removed->push_back(smsg.msg);
459 } else {
460 delete smsg.msg.pdata;
461 }
462 iter = sendlist_.erase(iter);
463 *smsg.ready = true;
464 smsg.thread->socketserver()->WakeUp();
465 continue;
466 }
467 ++iter;
468 }
469
470 MessageQueue::Clear(phandler, id, removed);
471}
472
kthelgason61abe152017-03-29 02:32:36 -0700473#if !defined(WEBRTC_MAC)
474// Note that these methods have a separate implementation for mac and ios
kjellandere96c45b2017-06-30 10:45:21 -0700475// defined in webrtc/rtc_base/thread_darwin.mm.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000476bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700477 // Using ProcessMessages with a custom clock for testing and a time greater
478 // than 0 doesn't work, since it's not guaranteed to advance the custom
479 // clock's time, and may get stuck in an infinite loop.
480 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
481 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700482 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000483 int cmsNext = cmsLoop;
484
485 while (true) {
kthelgasonde6adbe2017-02-22 00:42:11 -0800486 Message msg;
487 if (!Get(&msg, cmsNext))
488 return !IsQuitting();
489 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000490
kthelgasonde6adbe2017-02-22 00:42:11 -0800491 if (cmsLoop != kForever) {
492 cmsNext = static_cast<int>(TimeUntil(msEnd));
493 if (cmsNext < 0)
494 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000495 }
496 }
497}
kthelgason61abe152017-03-29 02:32:36 -0700498#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000499
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000500bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
501 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100502 RTC_DCHECK_RUN_ON(&thread_checker_);
503 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000504
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000505#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000506 if (need_synchronize_access) {
507 // We explicitly ask for no rights other than synchronization.
508 // This gives us the best chance of succeeding.
509 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
510 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100511 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000512 return false;
513 }
514 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000515 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000516#elif defined(WEBRTC_POSIX)
517 thread_ = pthread_self();
518#endif
519 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000520 thread_manager->SetCurrentThread(this);
521 return true;
522}
523
Tommi51492422017-12-04 15:18:23 +0100524bool Thread::IsRunning() {
525 RTC_DCHECK_RUN_ON(&thread_checker_);
526#if defined(WEBRTC_WIN)
527 return thread_ != nullptr;
528#elif defined(WEBRTC_POSIX)
529 return thread_ != 0;
530#endif
531}
532
tommie7251592017-07-14 14:44:46 -0700533AutoThread::AutoThread() : Thread(SocketServer::CreateDefault()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000534 if (!ThreadManager::Instance()->CurrentThread()) {
535 ThreadManager::Instance()->SetCurrentThread(this);
536 }
537}
538
539AutoThread::~AutoThread() {
540 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700541 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000542 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800543 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000544 }
545}
546
nisse7eaa4ea2017-05-08 05:25:41 -0700547AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
548 : Thread(ss) {
549 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100550 // Temporarily set the current thread to nullptr so that we can keep checks
551 // around that catch unintentional pointer overwrites.
552 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700553 rtc::ThreadManager::Instance()->SetCurrentThread(this);
554 if (old_thread_) {
555 MessageQueueManager::Remove(old_thread_);
556 }
557}
558
559AutoSocketServerThread::~AutoSocketServerThread() {
560 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
561 // Some tests post destroy messages to this thread. To avoid memory
562 // leaks, we have to process those messages. In particular
563 // P2PTransportChannelPingTest, relying on the message posted in
564 // cricket::Connection::Destroy.
565 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -0700566 // Stop and destroy the thread before clearing it as the current thread.
567 // Sometimes there are messages left in the MessageQueue that will be
568 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
569 // its contents rely on this thread still being set as the current thread.
570 Stop();
571 DoDestroy();
Tommi51492422017-12-04 15:18:23 +0100572 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700573 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
574 if (old_thread_) {
575 MessageQueueManager::Add(old_thread_);
576 }
577}
578
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000579} // namespace rtc