blob: 6dda76258abedc4a4e88a4d73380d0efa8ae6098 [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) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180 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) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100225 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226 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_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100243 RTC_LOG_GLE(LS_ERROR)
244 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000245 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800246 thread_ = nullptr;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000247 }
248#endif
249 running_.Reset();
250}
251
252void Thread::SafeWrapCurrent() {
253 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
254}
255
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256void Thread::Join() {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000257 if (running()) {
nisseede5da42017-01-12 05:15:36 -0800258 RTC_DCHECK(!IsCurrent());
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000259 if (Current() && !Current()->blocking_calls_allowed_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100260 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
261 << "but blocking calls have been disallowed";
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000262 }
263
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800265 RTC_DCHECK(thread_ != nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000266 WaitForSingleObject(thread_, INFINITE);
267 CloseHandle(thread_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800268 thread_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269 thread_id_ = 0;
270#elif defined(WEBRTC_POSIX)
271 void *pv;
272 pthread_join(thread_, &pv);
273#endif
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000274 running_.Reset();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275 }
276}
277
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000278bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800279 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000280 bool previous = blocking_calls_allowed_;
281 blocking_calls_allowed_ = allow;
282 return previous;
283}
284
285// static
286void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700287#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000288 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800289 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000290#endif
291}
292
deadbeefdc20e262017-01-31 15:10:44 -0800293// static
kthelgason61abe152017-03-29 02:32:36 -0700294#if !defined(WEBRTC_MAC)
deadbeefdc20e262017-01-31 15:10:44 -0800295#if defined(WEBRTC_WIN)
296DWORD WINAPI Thread::PreRun(LPVOID pv) {
297#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000298void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800299#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000300 ThreadInit* init = static_cast<ThreadInit*>(pv);
301 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200302 rtc::SetCurrentThreadName(init->thread->name_.c_str());
kthelgasonde6adbe2017-02-22 00:42:11 -0800303 if (init->runnable) {
304 init->runnable->Run(init->thread);
305 } else {
306 init->thread->Run();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307 }
kthelgasonde6adbe2017-02-22 00:42:11 -0800308 delete init;
309#ifdef WEBRTC_WIN
310 return 0;
311#else
312 return nullptr;
313#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314}
kthelgason61abe152017-03-29 02:32:36 -0700315#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316
317void Thread::Run() {
318 ProcessMessages(kForever);
319}
320
321bool Thread::IsOwned() {
322 return owned_;
323}
324
325void Thread::Stop() {
326 MessageQueue::Quit();
327 Join();
328}
329
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700330void Thread::Send(const Location& posted_from,
331 MessageHandler* phandler,
332 uint32_t id,
333 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200334 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335 return;
336
337 // Sent messages are sent to the MessageHandler directly, in the context
338 // of "thread", like Win32 SendMessage. If in the right context,
339 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000340 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700341 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000342 msg.phandler = phandler;
343 msg.message_id = id;
344 msg.pdata = pdata;
345 if (IsCurrent()) {
346 phandler->OnMessage(&msg);
347 return;
348 }
349
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000350 AssertBlockingIsAllowedOnCurrentThread();
351
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352 AutoThread thread;
353 Thread *current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800354 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355
356 bool ready = false;
357 {
358 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000359 _SendMessage smsg;
360 smsg.thread = current_thread;
361 smsg.msg = msg;
362 smsg.ready = &ready;
363 sendlist_.push_back(smsg);
364 }
365
366 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800367 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000368
369 bool waited = false;
370 crit_.Enter();
371 while (!ready) {
372 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000373 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
374 // thread invoking calls on the current thread.
375 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000376 current_thread->socketserver()->Wait(kForever, false);
377 waited = true;
378 crit_.Enter();
379 }
380 crit_.Leave();
381
382 // Our Wait loop above may have consumed some WakeUp events for this
383 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
384 // cause problems for some SocketServers.
385 //
386 // Concrete example:
387 // Win32SocketServer on thread A calls Send on thread B. While processing the
388 // message, thread B Posts a message to A. We consume the wakeup for that
389 // Post while waiting for the Send to complete, which means that when we exit
390 // this loop, we need to issue another WakeUp, or else the Posted message
391 // won't be processed in a timely manner.
392
393 if (waited) {
394 current_thread->socketserver()->WakeUp();
395 }
396}
397
398void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800399 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000400}
401
402void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000403 // Receive a sent message. Cleanup scenarios:
404 // - thread sending exits: We don't allow this, since thread can exit
405 // only via Join, so Send must complete.
406 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
407 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000408 _SendMessage smsg;
409
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000410 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000411 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000413
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000414 smsg.msg.phandler->OnMessage(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000415
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000416 crit_.Enter();
417 *smsg.ready = true;
418 smsg.thread->socketserver()->WakeUp();
419 }
420 crit_.Leave();
421}
422
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000423bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
424 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
425 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800426 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000427 *msg = *it;
428 sendlist_.erase(it);
429 return true;
430 }
431 }
432 return false;
433}
434
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700435void Thread::InvokeInternal(const Location& posted_from,
436 MessageHandler* handler) {
437 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
438 posted_from.file_and_line(), "src_func",
439 posted_from.function_name());
440 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000441}
442
Peter Boström0c4e06b2015-10-07 12:23:21 +0200443void Thread::Clear(MessageHandler* phandler,
444 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000445 MessageList* removed) {
446 CritScope cs(&crit_);
447
448 // Remove messages on sendlist_ with phandler
449 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800450 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000451
452 std::list<_SendMessage>::iterator iter = sendlist_.begin();
453 while (iter != sendlist_.end()) {
454 _SendMessage smsg = *iter;
455 if (smsg.msg.Match(phandler, id)) {
456 if (removed) {
457 removed->push_back(smsg.msg);
458 } else {
459 delete smsg.msg.pdata;
460 }
461 iter = sendlist_.erase(iter);
462 *smsg.ready = true;
463 smsg.thread->socketserver()->WakeUp();
464 continue;
465 }
466 ++iter;
467 }
468
469 MessageQueue::Clear(phandler, id, removed);
470}
471
kthelgason61abe152017-03-29 02:32:36 -0700472#if !defined(WEBRTC_MAC)
473// Note that these methods have a separate implementation for mac and ios
kjellandere96c45b2017-06-30 10:45:21 -0700474// defined in webrtc/rtc_base/thread_darwin.mm.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000475bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700476 // Using ProcessMessages with a custom clock for testing and a time greater
477 // than 0 doesn't work, since it's not guaranteed to advance the custom
478 // clock's time, and may get stuck in an infinite loop.
479 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
480 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700481 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000482 int cmsNext = cmsLoop;
483
484 while (true) {
kthelgasonde6adbe2017-02-22 00:42:11 -0800485 Message msg;
486 if (!Get(&msg, cmsNext))
487 return !IsQuitting();
488 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000489
kthelgasonde6adbe2017-02-22 00:42:11 -0800490 if (cmsLoop != kForever) {
491 cmsNext = static_cast<int>(TimeUntil(msEnd));
492 if (cmsNext < 0)
493 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000494 }
495 }
496}
kthelgason61abe152017-03-29 02:32:36 -0700497#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000498
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000499bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
500 bool need_synchronize_access) {
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000501 if (running())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000502 return false;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000503
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000504#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000505 if (need_synchronize_access) {
506 // We explicitly ask for no rights other than synchronization.
507 // This gives us the best chance of succeeding.
508 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
509 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100510 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000511 return false;
512 }
513 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000514 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000515#elif defined(WEBRTC_POSIX)
516 thread_ = pthread_self();
517#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000518
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000519 owned_ = false;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000520 running_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000521 thread_manager->SetCurrentThread(this);
522 return true;
523}
524
tommie7251592017-07-14 14:44:46 -0700525AutoThread::AutoThread() : Thread(SocketServer::CreateDefault()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000526 if (!ThreadManager::Instance()->CurrentThread()) {
527 ThreadManager::Instance()->SetCurrentThread(this);
528 }
529}
530
531AutoThread::~AutoThread() {
532 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700533 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000534 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800535 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000536 }
537}
538
nisse7eaa4ea2017-05-08 05:25:41 -0700539AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
540 : Thread(ss) {
541 old_thread_ = ThreadManager::Instance()->CurrentThread();
542 rtc::ThreadManager::Instance()->SetCurrentThread(this);
543 if (old_thread_) {
544 MessageQueueManager::Remove(old_thread_);
545 }
546}
547
548AutoSocketServerThread::~AutoSocketServerThread() {
549 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
550 // Some tests post destroy messages to this thread. To avoid memory
551 // leaks, we have to process those messages. In particular
552 // P2PTransportChannelPingTest, relying on the message posted in
553 // cricket::Connection::Destroy.
554 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -0700555 // Stop and destroy the thread before clearing it as the current thread.
556 // Sometimes there are messages left in the MessageQueue that will be
557 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
558 // its contents rely on this thread still being set as the current thread.
559 Stop();
560 DoDestroy();
nisse7eaa4ea2017-05-08 05:25:41 -0700561 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
562 if (old_thread_) {
563 MessageQueueManager::Add(old_thread_);
564 }
565}
566
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000567} // namespace rtc