blob: 373fa3952de37947e50bd6f29816ce0cdbab4177 [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
Artem Titov80d02ad2018-05-21 12:20:39 +020021#if defined(WEBRTC_WIN)
22// Disable warning that we don't care about:
23// warning C4722: destructor never returns, potential memory leak
24#pragma warning(disable : 4722)
25#endif
26
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/checks.h"
28#include "rtc_base/logging.h"
29#include "rtc_base/nullsocketserver.h"
30#include "rtc_base/platform_thread.h"
31#include "rtc_base/stringutils.h"
32#include "rtc_base/timeutils.h"
33#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000034
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035namespace rtc {
36
37ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +020038 static ThreadManager* const thread_manager = new ThreadManager();
39 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040}
41
nisse7866cfe2017-04-26 01:45:31 -070042ThreadManager::~ThreadManager() {
43 // By above RTC_DEFINE_STATIC_LOCAL.
44 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
45}
46
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000047// static
48Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -070049 ThreadManager* manager = ThreadManager::Instance();
50 Thread* thread = manager->CurrentThread();
51
52#ifndef NO_MAIN_THREAD_WRAPPING
53 // Only autowrap the thread which instantiated the ThreadManager.
54 if (!thread && manager->IsMainThread()) {
tommie7251592017-07-14 14:44:46 -070055 thread = new Thread(SocketServer::CreateDefault());
nisse7866cfe2017-04-26 01:45:31 -070056 thread->WrapCurrentWithThreadManager(manager, true);
57 }
58#endif
59
60 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000061}
62
63#if defined(WEBRTC_POSIX)
kthelgason61abe152017-03-29 02:32:36 -070064#if !defined(WEBRTC_MAC)
Tommi51492422017-12-04 15:18:23 +010065ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
deadbeef37f5ecf2017-02-27 14:06:41 -080066 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000067}
kthelgason61abe152017-03-29 02:32:36 -070068#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069
Yves Gerey665174f2018-06-19 15:03:05 +020070Thread* ThreadManager::CurrentThread() {
71 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072}
73
Tommi6f314bb2017-12-04 20:38:20 +010074void ThreadManager::SetCurrentThread(Thread* thread) {
75#if RTC_DLOG_IS_ON
76 if (CurrentThread() && thread) {
77 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
78 }
79#endif // RTC_DLOG_IS_ON
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080 pthread_setspecific(key_, thread);
81}
82#endif
83
84#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +010085ThreadManager::ThreadManager()
Yves Gerey665174f2018-06-19 15:03:05 +020086 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
87
88Thread* ThreadManager::CurrentThread() {
89 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090}
91
Yves Gerey665174f2018-06-19 15:03:05 +020092void ThreadManager::SetCurrentThread(Thread* thread) {
Tommi51492422017-12-04 15:18:23 +010093 RTC_DCHECK(!CurrentThread() || !thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094 TlsSetValue(key_, thread);
95}
96#endif
97
Yves Gerey665174f2018-06-19 15:03:05 +020098Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000099 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800100 if (nullptr == result) {
tommie7251592017-07-14 14:44:46 -0700101 result = new Thread(SocketServer::CreateDefault());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000102 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103 }
104 return result;
105}
106
107void ThreadManager::UnwrapCurrentThread() {
108 Thread* t = CurrentThread();
109 if (t && !(t->IsOwned())) {
110 t->UnwrapCurrent();
111 delete t;
112 }
113}
114
nisse7866cfe2017-04-26 01:45:31 -0700115bool ThreadManager::IsMainThread() {
116 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
117}
118
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000119Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200120 : thread_(Thread::Current()),
121 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000122
123Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800124 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000125 thread_->SetAllowBlockingCalls(previous_state_);
126}
127
tommie7251592017-07-14 14:44:46 -0700128// DEPRECATED.
danilchapbebf54c2016-04-28 01:32:48 -0700129Thread::Thread() : Thread(SocketServer::CreateDefault()) {}
130
Taylor Brandstetter08672602018-03-02 15:20:33 -0800131Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700132
133Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800134 : Thread(std::move(ss), /*do_init=*/true) {}
135
136Thread::Thread(SocketServer* ss, bool do_init)
137 : MessageQueue(ss, /*do_init=*/false) {
138 SetName("Thread", this); // default name
139 if (do_init) {
140 DoInit();
141 }
142}
143
144Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Tommi51492422017-12-04 15:18:23 +0100145 : MessageQueue(std::move(ss), false) {
danilchapbebf54c2016-04-28 01:32:48 -0700146 SetName("Thread", this); // default name
Taylor Brandstetter08672602018-03-02 15:20:33 -0800147 if (do_init) {
148 DoInit();
149 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000150}
151
152Thread::~Thread() {
153 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800154 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000155}
156
nisse7866cfe2017-04-26 01:45:31 -0700157bool Thread::IsCurrent() const {
158 return ThreadManager::Instance()->CurrentThread() == this;
159}
160
danilchapbebf54c2016-04-28 01:32:48 -0700161std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
162 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
163}
164
165std::unique_ptr<Thread> Thread::Create() {
166 return std::unique_ptr<Thread>(
167 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
168}
169
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000171 AssertBlockingIsAllowedOnCurrentThread();
172
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173#if defined(WEBRTC_WIN)
174 ::Sleep(milliseconds);
175 return true;
176#else
177 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
178 // so we use nanosleep() even though it has greater precision than necessary.
179 struct timespec ts;
180 ts.tv_sec = milliseconds / 1000;
181 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800182 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000183 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100184 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 return false;
186 }
187 return true;
188#endif
189}
190
191bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100192 RTC_DCHECK(!IsRunning());
193
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000194 name_ = name;
195 if (obj) {
196 char buf[16];
197 sprintfn(buf, sizeof(buf), " 0x%p", obj);
198 name_ += buf;
199 }
200 return true;
201}
202
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000203bool Thread::Start(Runnable* runnable) {
Tommi51492422017-12-04 15:18:23 +0100204 RTC_DCHECK(!IsRunning());
205
206 if (IsRunning())
207 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000208
André Susano Pinto02a57972016-07-22 13:30:05 +0200209 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210
211 // Make sure that ThreadManager is created on the main thread before
212 // we start a new thread.
213 ThreadManager::Instance();
214
Tommi51492422017-12-04 15:18:23 +0100215 owned_ = true;
216
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000217 ThreadInit* init = new ThreadInit;
218 init->thread = this;
219 init->runnable = runnable;
220#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800221 thread_ = CreateThread(nullptr, 0, PreRun, init, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100222 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223 return false;
224 }
225#elif defined(WEBRTC_POSIX)
226 pthread_attr_t attr;
227 pthread_attr_init(&attr);
228
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229 int error_code = pthread_create(&thread_, &attr, PreRun, init);
230 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100231 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100232 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000233 return false;
234 }
Tommi51492422017-12-04 15:18:23 +0100235 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000236#endif
237 return true;
238}
239
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000240bool Thread::WrapCurrent() {
241 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
242}
243
244void Thread::UnwrapCurrent() {
245 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800246 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000247#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800248 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000249 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100250 RTC_LOG_GLE(LS_ERROR)
251 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000252 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800253 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100254 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000255 }
Tommi51492422017-12-04 15:18:23 +0100256#elif defined(WEBRTC_POSIX)
257 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000258#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000259}
260
261void Thread::SafeWrapCurrent() {
262 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
263}
264
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100266 if (!IsRunning())
267 return;
268
269 RTC_DCHECK(!IsCurrent());
270 if (Current() && !Current()->blocking_calls_allowed_) {
271 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
272 << "but blocking calls have been disallowed";
273 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000274
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100276 RTC_DCHECK(thread_ != nullptr);
277 WaitForSingleObject(thread_, INFINITE);
278 CloseHandle(thread_);
279 thread_ = nullptr;
280 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100282 pthread_join(thread_, nullptr);
283 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000284#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000285}
286
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000287bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800288 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000289 bool previous = blocking_calls_allowed_;
290 blocking_calls_allowed_ = allow;
291 return previous;
292}
293
294// static
295void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700296#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000297 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800298 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000299#endif
300}
301
deadbeefdc20e262017-01-31 15:10:44 -0800302// static
kthelgason61abe152017-03-29 02:32:36 -0700303#if !defined(WEBRTC_MAC)
deadbeefdc20e262017-01-31 15:10:44 -0800304#if defined(WEBRTC_WIN)
305DWORD WINAPI Thread::PreRun(LPVOID pv) {
306#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800308#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309 ThreadInit* init = static_cast<ThreadInit*>(pv);
310 ThreadManager::Instance()->SetCurrentThread(init->thread);
Tommiea14f0a2015-05-18 13:51:06 +0200311 rtc::SetCurrentThreadName(init->thread->name_.c_str());
kthelgasonde6adbe2017-02-22 00:42:11 -0800312 if (init->runnable) {
313 init->runnable->Run(init->thread);
314 } else {
315 init->thread->Run();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316 }
Tommi51492422017-12-04 15:18:23 +0100317 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800318 delete init;
319#ifdef WEBRTC_WIN
320 return 0;
321#else
322 return nullptr;
323#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324}
kthelgason61abe152017-03-29 02:32:36 -0700325#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326
327void Thread::Run() {
328 ProcessMessages(kForever);
329}
330
331bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100332 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000333 return owned_;
334}
335
336void Thread::Stop() {
337 MessageQueue::Quit();
338 Join();
339}
340
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700341void Thread::Send(const Location& posted_from,
342 MessageHandler* phandler,
343 uint32_t id,
344 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200345 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000346 return;
347
348 // Sent messages are sent to the MessageHandler directly, in the context
349 // of "thread", like Win32 SendMessage. If in the right context,
350 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700352 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000353 msg.phandler = phandler;
354 msg.message_id = id;
355 msg.pdata = pdata;
356 if (IsCurrent()) {
357 phandler->OnMessage(&msg);
358 return;
359 }
360
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000361 AssertBlockingIsAllowedOnCurrentThread();
362
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000363 AutoThread thread;
Yves Gerey665174f2018-06-19 15:03:05 +0200364 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800365 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000366
367 bool ready = false;
368 {
369 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370 _SendMessage smsg;
371 smsg.thread = current_thread;
372 smsg.msg = msg;
373 smsg.ready = &ready;
374 sendlist_.push_back(smsg);
375 }
376
377 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800378 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000379
380 bool waited = false;
381 crit_.Enter();
382 while (!ready) {
383 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000384 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
385 // thread invoking calls on the current thread.
386 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000387 current_thread->socketserver()->Wait(kForever, false);
388 waited = true;
389 crit_.Enter();
390 }
391 crit_.Leave();
392
393 // Our Wait loop above may have consumed some WakeUp events for this
394 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
395 // cause problems for some SocketServers.
396 //
397 // Concrete example:
398 // Win32SocketServer on thread A calls Send on thread B. While processing the
399 // message, thread B Posts a message to A. We consume the wakeup for that
400 // Post while waiting for the Send to complete, which means that when we exit
401 // this loop, we need to issue another WakeUp, or else the Posted message
402 // won't be processed in a timely manner.
403
404 if (waited) {
405 current_thread->socketserver()->WakeUp();
406 }
407}
408
409void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800410 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000411}
412
413void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000414 // Receive a sent message. Cleanup scenarios:
415 // - thread sending exits: We don't allow this, since thread can exit
416 // only via Join, so Send must complete.
417 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
418 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000419 _SendMessage smsg;
420
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000421 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000422 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000423 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000424
Ishan Khota3b66012018-06-26 20:04:43 -0700425 Dispatch(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000426
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000427 crit_.Enter();
428 *smsg.ready = true;
429 smsg.thread->socketserver()->WakeUp();
430 }
431 crit_.Leave();
432}
433
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000434bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
435 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
436 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800437 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000438 *msg = *it;
439 sendlist_.erase(it);
440 return true;
441 }
442 }
443 return false;
444}
445
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700446void Thread::InvokeInternal(const Location& posted_from,
447 MessageHandler* handler) {
448 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
449 posted_from.file_and_line(), "src_func",
450 posted_from.function_name());
451 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000452}
453
Peter Boström0c4e06b2015-10-07 12:23:21 +0200454void Thread::Clear(MessageHandler* phandler,
455 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000456 MessageList* removed) {
457 CritScope cs(&crit_);
458
459 // Remove messages on sendlist_ with phandler
460 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800461 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000462
463 std::list<_SendMessage>::iterator iter = sendlist_.begin();
464 while (iter != sendlist_.end()) {
465 _SendMessage smsg = *iter;
466 if (smsg.msg.Match(phandler, id)) {
467 if (removed) {
468 removed->push_back(smsg.msg);
469 } else {
470 delete smsg.msg.pdata;
471 }
472 iter = sendlist_.erase(iter);
473 *smsg.ready = true;
474 smsg.thread->socketserver()->WakeUp();
475 continue;
476 }
477 ++iter;
478 }
479
480 MessageQueue::Clear(phandler, id, removed);
481}
482
kthelgason61abe152017-03-29 02:32:36 -0700483#if !defined(WEBRTC_MAC)
484// Note that these methods have a separate implementation for mac and ios
kjellandere96c45b2017-06-30 10:45:21 -0700485// defined in webrtc/rtc_base/thread_darwin.mm.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000486bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700487 // Using ProcessMessages with a custom clock for testing and a time greater
488 // than 0 doesn't work, since it's not guaranteed to advance the custom
489 // clock's time, and may get stuck in an infinite loop.
490 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
491 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700492 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000493 int cmsNext = cmsLoop;
494
495 while (true) {
kthelgasonde6adbe2017-02-22 00:42:11 -0800496 Message msg;
497 if (!Get(&msg, cmsNext))
498 return !IsQuitting();
499 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000500
kthelgasonde6adbe2017-02-22 00:42:11 -0800501 if (cmsLoop != kForever) {
502 cmsNext = static_cast<int>(TimeUntil(msEnd));
503 if (cmsNext < 0)
504 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000505 }
506 }
507}
kthelgason61abe152017-03-29 02:32:36 -0700508#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000509
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000510bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
511 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100512 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000513
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000514#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000515 if (need_synchronize_access) {
516 // We explicitly ask for no rights other than synchronization.
517 // This gives us the best chance of succeeding.
518 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
519 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100520 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000521 return false;
522 }
523 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000524 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000525#elif defined(WEBRTC_POSIX)
526 thread_ = pthread_self();
527#endif
528 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000529 thread_manager->SetCurrentThread(this);
530 return true;
531}
532
Tommi51492422017-12-04 15:18:23 +0100533bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +0100534#if defined(WEBRTC_WIN)
535 return thread_ != nullptr;
536#elif defined(WEBRTC_POSIX)
537 return thread_ != 0;
538#endif
539}
540
Taylor Brandstetter08672602018-03-02 15:20:33 -0800541AutoThread::AutoThread()
542 : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
543 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000544 if (!ThreadManager::Instance()->CurrentThread()) {
545 ThreadManager::Instance()->SetCurrentThread(this);
546 }
547}
548
549AutoThread::~AutoThread() {
550 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700551 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000552 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800553 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000554 }
555}
556
nisse7eaa4ea2017-05-08 05:25:41 -0700557AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800558 : Thread(ss, /*do_init=*/false) {
559 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -0700560 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100561 // Temporarily set the current thread to nullptr so that we can keep checks
562 // around that catch unintentional pointer overwrites.
563 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700564 rtc::ThreadManager::Instance()->SetCurrentThread(this);
565 if (old_thread_) {
566 MessageQueueManager::Remove(old_thread_);
567 }
568}
569
570AutoSocketServerThread::~AutoSocketServerThread() {
571 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
572 // Some tests post destroy messages to this thread. To avoid memory
573 // leaks, we have to process those messages. In particular
574 // P2PTransportChannelPingTest, relying on the message posted in
575 // cricket::Connection::Destroy.
576 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -0700577 // Stop and destroy the thread before clearing it as the current thread.
578 // Sometimes there are messages left in the MessageQueue that will be
579 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
580 // its contents rely on this thread still being set as the current thread.
581 Stop();
582 DoDestroy();
Tommi51492422017-12-04 15:18:23 +0100583 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700584 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
585 if (old_thread_) {
586 MessageQueueManager::Add(old_thread_);
587 }
588}
589
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000590} // namespace rtc