blob: 1bc0c0cd8581304808946297cd355a9cad64c7c5 [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>
17#endif
18
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/checks.h"
20#include "rtc_base/logging.h"
21#include "rtc_base/nullsocketserver.h"
22#include "rtc_base/platform_thread.h"
23#include "rtc_base/stringutils.h"
24#include "rtc_base/timeutils.h"
25#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027namespace rtc {
28
29ThreadManager* ThreadManager::Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -070030 RTC_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000031 return &thread_manager;
32}
33
nisse7866cfe2017-04-26 01:45:31 -070034ThreadManager::~ThreadManager() {
35 // By above RTC_DEFINE_STATIC_LOCAL.
36 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
37}
38
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039// static
40Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -070041 ThreadManager* manager = ThreadManager::Instance();
42 Thread* thread = manager->CurrentThread();
43
44#ifndef NO_MAIN_THREAD_WRAPPING
45 // Only autowrap the thread which instantiated the ThreadManager.
46 if (!thread && manager->IsMainThread()) {
tommie7251592017-07-14 14:44:46 -070047 thread = new Thread(SocketServer::CreateDefault());
nisse7866cfe2017-04-26 01:45:31 -070048 thread->WrapCurrentWithThreadManager(manager, true);
49 }
50#endif
51
52 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053}
54
55#if defined(WEBRTC_POSIX)
kthelgason61abe152017-03-29 02:32:36 -070056#if !defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057ThreadManager::ThreadManager() {
nisse7866cfe2017-04-26 01:45:31 -070058 main_thread_ref_ = CurrentThreadRef();
deadbeef37f5ecf2017-02-27 14:06:41 -080059 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060}
kthelgason61abe152017-03-29 02:32:36 -070061#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062
63Thread *ThreadManager::CurrentThread() {
64 return static_cast<Thread *>(pthread_getspecific(key_));
65}
66
67void ThreadManager::SetCurrentThread(Thread *thread) {
68 pthread_setspecific(key_, thread);
69}
70#endif
71
72#if defined(WEBRTC_WIN)
73ThreadManager::ThreadManager() {
nisse7866cfe2017-04-26 01:45:31 -070074 main_thread_ref_ = CurrentThreadRef();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000075 key_ = TlsAlloc();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000076}
77
78Thread *ThreadManager::CurrentThread() {
79 return static_cast<Thread *>(TlsGetValue(key_));
80}
81
82void ThreadManager::SetCurrentThread(Thread *thread) {
83 TlsSetValue(key_, thread);
84}
85#endif
86
87Thread *ThreadManager::WrapCurrentThread() {
88 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -080089 if (nullptr == result) {
tommie7251592017-07-14 14:44:46 -070090 result = new Thread(SocketServer::CreateDefault());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +000091 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092 }
93 return result;
94}
95
96void ThreadManager::UnwrapCurrentThread() {
97 Thread* t = CurrentThread();
98 if (t && !(t->IsOwned())) {
99 t->UnwrapCurrent();
100 delete t;
101 }
102}
103
nisse7866cfe2017-04-26 01:45:31 -0700104bool ThreadManager::IsMainThread() {
105 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
106}
107
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000108Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
109 : thread_(Thread::Current()),
110 previous_state_(thread_->SetAllowBlockingCalls(false)) {
111}
112
113Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800114 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000115 thread_->SetAllowBlockingCalls(previous_state_);
116}
117
tommie7251592017-07-14 14:44:46 -0700118// DEPRECATED.
danilchapbebf54c2016-04-28 01:32:48 -0700119Thread::Thread() : Thread(SocketServer::CreateDefault()) {}
120
121Thread::Thread(SocketServer* ss)
jbauch25d1f282016-02-05 00:25:02 -0800122 : MessageQueue(ss, false),
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000123 running_(true, false),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800125 thread_(nullptr),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126 thread_id_(0),
127#endif
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000128 owned_(true),
129 blocking_calls_allowed_(true) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000130 SetName("Thread", this); // default name
danilchapbebf54c2016-04-28 01:32:48 -0700131 DoInit();
132}
133
134Thread::Thread(std::unique_ptr<SocketServer> ss)
135 : MessageQueue(std::move(ss), false),
136 running_(true, false),
137#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800138 thread_(nullptr),
danilchapbebf54c2016-04-28 01:32:48 -0700139 thread_id_(0),
140#endif
141 owned_(true),
142 blocking_calls_allowed_(true) {
143 SetName("Thread", this); // default name
144 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145}
146
147Thread::~Thread() {
148 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800149 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000150}
151
nisse7866cfe2017-04-26 01:45:31 -0700152bool Thread::IsCurrent() const {
153 return ThreadManager::Instance()->CurrentThread() == this;
154}
155
danilchapbebf54c2016-04-28 01:32:48 -0700156std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
157 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
158}
159
160std::unique_ptr<Thread> Thread::Create() {
161 return std::unique_ptr<Thread>(
162 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
163}
164
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000166 AssertBlockingIsAllowedOnCurrentThread();
167
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000168#if defined(WEBRTC_WIN)
169 ::Sleep(milliseconds);
170 return true;
171#else
172 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
173 // so we use nanosleep() even though it has greater precision than necessary.
174 struct timespec ts;
175 ts.tv_sec = milliseconds / 1000;
176 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800177 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178 if (ret != 0) {
179 LOG_ERR(LS_WARNING) << "nanosleep() returning early";
180 return false;
181 }
182 return true;
183#endif
184}
185
186bool Thread::SetName(const std::string& name, const void* obj) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000187 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000188 name_ = name;
189 if (obj) {
190 char buf[16];
191 sprintfn(buf, sizeof(buf), " 0x%p", obj);
192 name_ += buf;
193 }
194 return true;
195}
196
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000197bool Thread::Start(Runnable* runnable) {
nisseede5da42017-01-12 05:15:36 -0800198 RTC_DCHECK(owned_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199 if (!owned_) return false;
nisseede5da42017-01-12 05:15:36 -0800200 RTC_DCHECK(!running());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000201 if (running()) return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000202
André Susano Pinto02a57972016-07-22 13:30:05 +0200203 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000204
205 // Make sure that ThreadManager is created on the main thread before
206 // we start a new thread.
207 ThreadManager::Instance();
208
209 ThreadInit* init = new ThreadInit;
210 init->thread = this;
211 init->runnable = runnable;
212#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800213 thread_ = CreateThread(nullptr, 0, PreRun, init, 0, &thread_id_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214 if (thread_) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000215 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216 } else {
217 return false;
218 }
219#elif defined(WEBRTC_POSIX)
220 pthread_attr_t attr;
221 pthread_attr_init(&attr);
222
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223 int error_code = pthread_create(&thread_, &attr, PreRun, init);
224 if (0 != error_code) {
225 LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
226 return false;
227 }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000228 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229#endif
230 return true;
231}
232
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000233bool Thread::WrapCurrent() {
234 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
235}
236
237void Thread::UnwrapCurrent() {
238 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800239 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000240#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800241 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000242 if (!CloseHandle(thread_)) {
243 LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
244 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800245 thread_ = nullptr;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000246 }
247#endif
248 running_.Reset();
249}
250
251void Thread::SafeWrapCurrent() {
252 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
253}
254
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255void Thread::Join() {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000256 if (running()) {
nisseede5da42017-01-12 05:15:36 -0800257 RTC_DCHECK(!IsCurrent());
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000258 if (Current() && !Current()->blocking_calls_allowed_) {
259 LOG(LS_WARNING) << "Waiting for the thread to join, "
260 << "but blocking calls have been disallowed";
261 }
262
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800264 RTC_DCHECK(thread_ != nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265 WaitForSingleObject(thread_, INFINITE);
266 CloseHandle(thread_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800267 thread_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000268 thread_id_ = 0;
269#elif defined(WEBRTC_POSIX)
270 void *pv;
271 pthread_join(thread_, &pv);
272#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000273 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000274 }
275}
276
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000277bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800278 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000279 bool previous = blocking_calls_allowed_;
280 blocking_calls_allowed_ = allow;
281 return previous;
282}
283
284// static
285void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700286#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000287 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800288 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000289#endif
290}
291
deadbeefdc20e262017-01-31 15:10:44 -0800292// static
kthelgason61abe152017-03-29 02:32:36 -0700293#if !defined(WEBRTC_MAC)
deadbeefdc20e262017-01-31 15:10:44 -0800294#if defined(WEBRTC_WIN)
295DWORD WINAPI Thread::PreRun(LPVOID pv) {
296#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000297void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800298#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299 ThreadInit* init = static_cast<ThreadInit*>(pv);
300 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200301 rtc::SetCurrentThreadName(init->thread->name_.c_str());
kthelgasonde6adbe2017-02-22 00:42:11 -0800302 if (init->runnable) {
303 init->runnable->Run(init->thread);
304 } else {
305 init->thread->Run();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306 }
kthelgasonde6adbe2017-02-22 00:42:11 -0800307 delete init;
308#ifdef WEBRTC_WIN
309 return 0;
310#else
311 return nullptr;
312#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313}
kthelgason61abe152017-03-29 02:32:36 -0700314#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000315
316void Thread::Run() {
317 ProcessMessages(kForever);
318}
319
320bool Thread::IsOwned() {
321 return owned_;
322}
323
324void Thread::Stop() {
325 MessageQueue::Quit();
326 Join();
327}
328
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700329void Thread::Send(const Location& posted_from,
330 MessageHandler* phandler,
331 uint32_t id,
332 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200333 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334 return;
335
336 // Sent messages are sent to the MessageHandler directly, in the context
337 // of "thread", like Win32 SendMessage. If in the right context,
338 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000339 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700340 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341 msg.phandler = phandler;
342 msg.message_id = id;
343 msg.pdata = pdata;
344 if (IsCurrent()) {
345 phandler->OnMessage(&msg);
346 return;
347 }
348
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000349 AssertBlockingIsAllowedOnCurrentThread();
350
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351 AutoThread thread;
352 Thread *current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800353 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000354
355 bool ready = false;
356 {
357 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000358 _SendMessage smsg;
359 smsg.thread = current_thread;
360 smsg.msg = msg;
361 smsg.ready = &ready;
362 sendlist_.push_back(smsg);
363 }
364
365 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800366 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000367
368 bool waited = false;
369 crit_.Enter();
370 while (!ready) {
371 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000372 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
373 // thread invoking calls on the current thread.
374 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375 current_thread->socketserver()->Wait(kForever, false);
376 waited = true;
377 crit_.Enter();
378 }
379 crit_.Leave();
380
381 // Our Wait loop above may have consumed some WakeUp events for this
382 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
383 // cause problems for some SocketServers.
384 //
385 // Concrete example:
386 // Win32SocketServer on thread A calls Send on thread B. While processing the
387 // message, thread B Posts a message to A. We consume the wakeup for that
388 // Post while waiting for the Send to complete, which means that when we exit
389 // this loop, we need to issue another WakeUp, or else the Posted message
390 // won't be processed in a timely manner.
391
392 if (waited) {
393 current_thread->socketserver()->WakeUp();
394 }
395}
396
397void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800398 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000399}
400
401void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000402 // Receive a sent message. Cleanup scenarios:
403 // - thread sending exits: We don't allow this, since thread can exit
404 // only via Join, so Send must complete.
405 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
406 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000407 _SendMessage smsg;
408
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000409 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000410 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000411 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000412
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000413 smsg.msg.phandler->OnMessage(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000414
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000415 crit_.Enter();
416 *smsg.ready = true;
417 smsg.thread->socketserver()->WakeUp();
418 }
419 crit_.Leave();
420}
421
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000422bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
423 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
424 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800425 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000426 *msg = *it;
427 sendlist_.erase(it);
428 return true;
429 }
430 }
431 return false;
432}
433
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700434void Thread::InvokeInternal(const Location& posted_from,
435 MessageHandler* handler) {
436 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
437 posted_from.file_and_line(), "src_func",
438 posted_from.function_name());
439 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000440}
441
Peter Boström0c4e06b2015-10-07 12:23:21 +0200442void Thread::Clear(MessageHandler* phandler,
443 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000444 MessageList* removed) {
445 CritScope cs(&crit_);
446
447 // Remove messages on sendlist_ with phandler
448 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800449 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000450
451 std::list<_SendMessage>::iterator iter = sendlist_.begin();
452 while (iter != sendlist_.end()) {
453 _SendMessage smsg = *iter;
454 if (smsg.msg.Match(phandler, id)) {
455 if (removed) {
456 removed->push_back(smsg.msg);
457 } else {
458 delete smsg.msg.pdata;
459 }
460 iter = sendlist_.erase(iter);
461 *smsg.ready = true;
462 smsg.thread->socketserver()->WakeUp();
463 continue;
464 }
465 ++iter;
466 }
467
468 MessageQueue::Clear(phandler, id, removed);
469}
470
kthelgason61abe152017-03-29 02:32:36 -0700471#if !defined(WEBRTC_MAC)
472// Note that these methods have a separate implementation for mac and ios
kjellandere96c45b2017-06-30 10:45:21 -0700473// defined in webrtc/rtc_base/thread_darwin.mm.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000474bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700475 // Using ProcessMessages with a custom clock for testing and a time greater
476 // than 0 doesn't work, since it's not guaranteed to advance the custom
477 // clock's time, and may get stuck in an infinite loop.
478 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
479 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700480 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000481 int cmsNext = cmsLoop;
482
483 while (true) {
kthelgasonde6adbe2017-02-22 00:42:11 -0800484 Message msg;
485 if (!Get(&msg, cmsNext))
486 return !IsQuitting();
487 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000488
kthelgasonde6adbe2017-02-22 00:42:11 -0800489 if (cmsLoop != kForever) {
490 cmsNext = static_cast<int>(TimeUntil(msEnd));
491 if (cmsNext < 0)
492 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000493 }
494 }
495}
kthelgason61abe152017-03-29 02:32:36 -0700496#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000497
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000498bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
499 bool need_synchronize_access) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000500 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000501 return false;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000502
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000503#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000504 if (need_synchronize_access) {
505 // We explicitly ask for no rights other than synchronization.
506 // This gives us the best chance of succeeding.
507 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
508 if (!thread_) {
509 LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
510 return false;
511 }
512 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000513 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000514#elif defined(WEBRTC_POSIX)
515 thread_ = pthread_self();
516#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000517
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000518 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000519 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000520 thread_manager->SetCurrentThread(this);
521 return true;
522}
523
tommie7251592017-07-14 14:44:46 -0700524AutoThread::AutoThread() : Thread(SocketServer::CreateDefault()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000525 if (!ThreadManager::Instance()->CurrentThread()) {
526 ThreadManager::Instance()->SetCurrentThread(this);
527 }
528}
529
530AutoThread::~AutoThread() {
531 Stop();
532 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800533 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000534 }
535}
536
nisse7eaa4ea2017-05-08 05:25:41 -0700537AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
538 : Thread(ss) {
539 old_thread_ = ThreadManager::Instance()->CurrentThread();
540 rtc::ThreadManager::Instance()->SetCurrentThread(this);
541 if (old_thread_) {
542 MessageQueueManager::Remove(old_thread_);
543 }
544}
545
546AutoSocketServerThread::~AutoSocketServerThread() {
547 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
548 // Some tests post destroy messages to this thread. To avoid memory
549 // leaks, we have to process those messages. In particular
550 // P2PTransportChannelPingTest, relying on the message posted in
551 // cricket::Connection::Destroy.
552 ProcessMessages(0);
553 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
554 if (old_thread_) {
555 MessageQueueManager::Add(old_thread_);
556 }
557}
558
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000559} // namespace rtc