blob: 7335af7c15d50b92e028893751867cd6d3908bdf [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
Yves Gerey988cc082018-10-23 12:03:01 +020027#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020028
Yves Gerey988cc082018-10-23 12:03:01 +020029#include <utility>
Yves Gerey2e00abc2018-10-05 15:39:24 +020030
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/null_socket_server.h"
35#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/trace_event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020038#if defined(WEBRTC_MAC)
39#include "rtc_base/system/cocoa_threading.h"
Yves Gerey988cc082018-10-23 12:03:01 +020040
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020041/*
42 * These are forward-declarations for methods that are part of the
43 * ObjC runtime. They are declared in the private header objc-internal.h.
44 * These calls are what clang inserts when using @autoreleasepool in ObjC,
45 * but here they are used directly in order to keep this file C++.
46 * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
47 */
48extern "C" {
49void* objc_autoreleasePoolPush(void);
50void objc_autoreleasePoolPop(void* pool);
51}
52
53namespace {
54class ScopedAutoReleasePool {
55 public:
56 ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
57 ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
58
59 private:
60 void* const pool_;
61};
62} // namespace
63#endif
64
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065namespace rtc {
Steve Antonbcc1a762019-12-11 11:21:53 -080066namespace {
67
68class MessageHandlerWithTask final : public MessageHandler {
69 public:
70 MessageHandlerWithTask() = default;
71
72 void OnMessage(Message* msg) override {
73 static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
74 delete msg->pdata;
75 }
76
77 private:
78 ~MessageHandlerWithTask() override {}
79
80 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
81};
82
83} // namespace
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000084
85ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +020086 static ThreadManager* const thread_manager = new ThreadManager();
87 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088}
89
nisse7866cfe2017-04-26 01:45:31 -070090ThreadManager::~ThreadManager() {
91 // By above RTC_DEFINE_STATIC_LOCAL.
92 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
93}
94
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000095// static
96Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -070097 ThreadManager* manager = ThreadManager::Instance();
98 Thread* thread = manager->CurrentThread();
99
Niels Moller9d1840c2019-05-21 07:26:37 +0000100#ifndef NO_MAIN_THREAD_WRAPPING
101 // Only autowrap the thread which instantiated the ThreadManager.
102 if (!thread && manager->IsMainThread()) {
103 thread = new Thread(SocketServer::CreateDefault());
104 thread->WrapCurrentWithThreadManager(manager, true);
105 }
106#endif
107
nisse7866cfe2017-04-26 01:45:31 -0700108 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000109}
110
111#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +0000112ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200113#if defined(WEBRTC_MAC)
114 InitCocoaMultiThreading();
115#endif
deadbeef37f5ecf2017-02-27 14:06:41 -0800116 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000117}
118
Yves Gerey665174f2018-06-19 15:03:05 +0200119Thread* ThreadManager::CurrentThread() {
120 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121}
122
Tommi6f314bb2017-12-04 20:38:20 +0100123void ThreadManager::SetCurrentThread(Thread* thread) {
124#if RTC_DLOG_IS_ON
125 if (CurrentThread() && thread) {
126 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
127 }
128#endif // RTC_DLOG_IS_ON
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129 pthread_setspecific(key_, thread);
130}
131#endif
132
133#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000134ThreadManager::ThreadManager()
135 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200136
137Thread* ThreadManager::CurrentThread() {
138 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139}
140
Yves Gerey665174f2018-06-19 15:03:05 +0200141void ThreadManager::SetCurrentThread(Thread* thread) {
Tommi51492422017-12-04 15:18:23 +0100142 RTC_DCHECK(!CurrentThread() || !thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143 TlsSetValue(key_, thread);
144}
145#endif
146
Yves Gerey665174f2018-06-19 15:03:05 +0200147Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000148 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800149 if (nullptr == result) {
tommie7251592017-07-14 14:44:46 -0700150 result = new Thread(SocketServer::CreateDefault());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000151 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152 }
153 return result;
154}
155
156void ThreadManager::UnwrapCurrentThread() {
157 Thread* t = CurrentThread();
158 if (t && !(t->IsOwned())) {
159 t->UnwrapCurrent();
160 delete t;
161 }
162}
163
Niels Moller9d1840c2019-05-21 07:26:37 +0000164bool ThreadManager::IsMainThread() {
165 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
166}
167
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000168Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200169 : thread_(Thread::Current()),
170 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000171
172Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800173 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000174 thread_->SetAllowBlockingCalls(previous_state_);
175}
176
Taylor Brandstetter08672602018-03-02 15:20:33 -0800177Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700178
179Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800180 : Thread(std::move(ss), /*do_init=*/true) {}
181
182Thread::Thread(SocketServer* ss, bool do_init)
183 : MessageQueue(ss, /*do_init=*/false) {
184 SetName("Thread", this); // default name
185 if (do_init) {
186 DoInit();
187 }
188}
189
190Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Tommi51492422017-12-04 15:18:23 +0100191 : MessageQueue(std::move(ss), false) {
danilchapbebf54c2016-04-28 01:32:48 -0700192 SetName("Thread", this); // default name
Taylor Brandstetter08672602018-03-02 15:20:33 -0800193 if (do_init) {
194 DoInit();
195 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196}
197
198Thread::~Thread() {
199 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800200 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000201}
202
nisse7866cfe2017-04-26 01:45:31 -0700203bool Thread::IsCurrent() const {
204 return ThreadManager::Instance()->CurrentThread() == this;
205}
206
danilchapbebf54c2016-04-28 01:32:48 -0700207std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
208 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
209}
210
211std::unique_ptr<Thread> Thread::Create() {
212 return std::unique_ptr<Thread>(
213 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
214}
215
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000217 AssertBlockingIsAllowedOnCurrentThread();
218
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000219#if defined(WEBRTC_WIN)
220 ::Sleep(milliseconds);
221 return true;
222#else
223 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
224 // so we use nanosleep() even though it has greater precision than necessary.
225 struct timespec ts;
226 ts.tv_sec = milliseconds / 1000;
227 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800228 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100230 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000231 return false;
232 }
233 return true;
234#endif
235}
236
237bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100238 RTC_DCHECK(!IsRunning());
239
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240 name_ = name;
241 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200242 // The %p specifier typically produce at most 16 hex digits, possibly with a
243 // 0x prefix. But format is implementation defined, so add some margin.
244 char buf[30];
245 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246 name_ += buf;
247 }
248 return true;
249}
250
Niels Möllerd2e50132019-06-11 09:24:14 +0200251bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100252 RTC_DCHECK(!IsRunning());
253
254 if (IsRunning())
255 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256
André Susano Pinto02a57972016-07-22 13:30:05 +0200257 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258
259 // Make sure that ThreadManager is created on the main thread before
260 // we start a new thread.
261 ThreadManager::Instance();
262
Tommi51492422017-12-04 15:18:23 +0100263 owned_ = true;
264
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200266 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100267 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000268 return false;
269 }
270#elif defined(WEBRTC_POSIX)
271 pthread_attr_t attr;
272 pthread_attr_init(&attr);
273
Niels Möllerd2e50132019-06-11 09:24:14 +0200274 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100276 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100277 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278 return false;
279 }
Tommi51492422017-12-04 15:18:23 +0100280 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281#endif
282 return true;
283}
284
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000285bool Thread::WrapCurrent() {
286 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
287}
288
289void Thread::UnwrapCurrent() {
290 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800291 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000292#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800293 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000294 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100295 RTC_LOG_GLE(LS_ERROR)
296 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000297 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800298 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100299 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000300 }
Tommi51492422017-12-04 15:18:23 +0100301#elif defined(WEBRTC_POSIX)
302 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000303#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000304}
305
306void Thread::SafeWrapCurrent() {
307 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
308}
309
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100311 if (!IsRunning())
312 return;
313
314 RTC_DCHECK(!IsCurrent());
315 if (Current() && !Current()->blocking_calls_allowed_) {
316 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
317 << "but blocking calls have been disallowed";
318 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000319
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100321 RTC_DCHECK(thread_ != nullptr);
322 WaitForSingleObject(thread_, INFINITE);
323 CloseHandle(thread_);
324 thread_ = nullptr;
325 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100327 pthread_join(thread_, nullptr);
328 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000329#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330}
331
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000332bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800333 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000334 bool previous = blocking_calls_allowed_;
335 blocking_calls_allowed_ = allow;
336 return previous;
337}
338
339// static
340void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700341#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000342 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800343 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000344#endif
345}
346
deadbeefdc20e262017-01-31 15:10:44 -0800347// static
348#if defined(WEBRTC_WIN)
349DWORD WINAPI Thread::PreRun(LPVOID pv) {
350#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800352#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200353 Thread* thread = static_cast<Thread*>(pv);
354 ThreadManager::Instance()->SetCurrentThread(thread);
355 rtc::SetCurrentThreadName(thread->name_.c_str());
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100356 CurrentTaskQueueSetter set_current_task_queue(thread);
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200357#if defined(WEBRTC_MAC)
358 ScopedAutoReleasePool pool;
359#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200360 thread->Run();
361
Tommi51492422017-12-04 15:18:23 +0100362 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800363#ifdef WEBRTC_WIN
364 return 0;
365#else
366 return nullptr;
367#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200368} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000369
370void Thread::Run() {
371 ProcessMessages(kForever);
372}
373
374bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100375 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000376 return owned_;
377}
378
379void Thread::Stop() {
380 MessageQueue::Quit();
381 Join();
382}
383
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700384void Thread::Send(const Location& posted_from,
385 MessageHandler* phandler,
386 uint32_t id,
387 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200388 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000389 return;
390
391 // Sent messages are sent to the MessageHandler directly, in the context
392 // of "thread", like Win32 SendMessage. If in the right context,
393 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000394 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700395 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000396 msg.phandler = phandler;
397 msg.message_id = id;
398 msg.pdata = pdata;
399 if (IsCurrent()) {
400 phandler->OnMessage(&msg);
401 return;
402 }
403
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000404 AssertBlockingIsAllowedOnCurrentThread();
405
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000406 AutoThread thread;
Yves Gerey665174f2018-06-19 15:03:05 +0200407 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800408 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000409
410 bool ready = false;
411 {
412 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000413 _SendMessage smsg;
414 smsg.thread = current_thread;
415 smsg.msg = msg;
416 smsg.ready = &ready;
417 sendlist_.push_back(smsg);
418 }
419
420 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800421 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000422
423 bool waited = false;
424 crit_.Enter();
425 while (!ready) {
426 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000427 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
428 // thread invoking calls on the current thread.
429 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000430 current_thread->socketserver()->Wait(kForever, false);
431 waited = true;
432 crit_.Enter();
433 }
434 crit_.Leave();
435
436 // Our Wait loop above may have consumed some WakeUp events for this
437 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
438 // cause problems for some SocketServers.
439 //
440 // Concrete example:
441 // Win32SocketServer on thread A calls Send on thread B. While processing the
442 // message, thread B Posts a message to A. We consume the wakeup for that
443 // Post while waiting for the Send to complete, which means that when we exit
444 // this loop, we need to issue another WakeUp, or else the Posted message
445 // won't be processed in a timely manner.
446
447 if (waited) {
448 current_thread->socketserver()->WakeUp();
449 }
450}
451
452void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800453 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000454}
455
456void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000457 // Receive a sent message. Cleanup scenarios:
458 // - thread sending exits: We don't allow this, since thread can exit
459 // only via Join, so Send must complete.
460 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
461 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000462 _SendMessage smsg;
463
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000464 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000465 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000466 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000467
Ishan Khota3b66012018-06-26 20:04:43 -0700468 Dispatch(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000469
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000470 crit_.Enter();
471 *smsg.ready = true;
472 smsg.thread->socketserver()->WakeUp();
473 }
474 crit_.Leave();
475}
476
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000477bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
478 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
479 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800480 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000481 *msg = *it;
482 sendlist_.erase(it);
483 return true;
484 }
485 }
486 return false;
487}
488
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700489void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100490 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800491 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
492 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100493
494 class FunctorMessageHandler : public MessageHandler {
495 public:
496 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
497 : functor_(functor) {}
498 void OnMessage(Message* msg) override { functor_(); }
499
500 private:
501 rtc::FunctionView<void()> functor_;
502 } handler(functor);
503
504 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000505}
506
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100507void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
508 RTC_DCHECK(msg);
509 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
510 std::unique_ptr<webrtc::QueuedTask> task = std::move(data->data());
511 // MessageQueue expects handler to own Message::pdata when OnMessage is called
512 // Since MessageData is no longer needed, delete it.
513 delete data;
514
515 // QueuedTask interface uses Run return value to communicate who owns the
516 // task. false means QueuedTask took the ownership.
517 if (!task->Run())
518 task.release();
519}
520
521void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
522 // Though Post takes MessageData by raw pointer (last parameter), it still
523 // takes it with ownership.
524 Post(RTC_FROM_HERE, &queued_task_handler_,
525 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
526}
527
528void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
529 uint32_t milliseconds) {
530 // Though PostDelayed takes MessageData by raw pointer (last parameter),
531 // it still takes it with ownership.
532 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
533 /*id=*/0,
534 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
535}
536
537void Thread::Delete() {
538 Stop();
539 delete this;
540}
541
Niels Möller8909a632018-09-06 08:42:44 +0200542bool Thread::IsProcessingMessagesForTesting() {
543 return (owned_ || IsCurrent()) &&
544 MessageQueue::IsProcessingMessagesForTesting();
545}
546
Peter Boström0c4e06b2015-10-07 12:23:21 +0200547void Thread::Clear(MessageHandler* phandler,
548 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549 MessageList* removed) {
550 CritScope cs(&crit_);
551
552 // Remove messages on sendlist_ with phandler
553 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800554 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000555
556 std::list<_SendMessage>::iterator iter = sendlist_.begin();
557 while (iter != sendlist_.end()) {
558 _SendMessage smsg = *iter;
559 if (smsg.msg.Match(phandler, id)) {
560 if (removed) {
561 removed->push_back(smsg.msg);
562 } else {
563 delete smsg.msg.pdata;
564 }
565 iter = sendlist_.erase(iter);
566 *smsg.ready = true;
567 smsg.thread->socketserver()->WakeUp();
568 continue;
569 }
570 ++iter;
571 }
572
Niels Möller5e007b72018-09-07 12:35:44 +0200573 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000574}
575
576bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700577 // Using ProcessMessages with a custom clock for testing and a time greater
578 // than 0 doesn't work, since it's not guaranteed to advance the custom
579 // clock's time, and may get stuck in an infinite loop.
580 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
581 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700582 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000583 int cmsNext = cmsLoop;
584
585 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200586#if defined(WEBRTC_MAC)
587 ScopedAutoReleasePool pool;
588#endif
kthelgasonde6adbe2017-02-22 00:42:11 -0800589 Message msg;
590 if (!Get(&msg, cmsNext))
591 return !IsQuitting();
592 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000593
kthelgasonde6adbe2017-02-22 00:42:11 -0800594 if (cmsLoop != kForever) {
595 cmsNext = static_cast<int>(TimeUntil(msEnd));
596 if (cmsNext < 0)
597 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000598 }
599 }
600}
601
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000602bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
603 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100604 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000605
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000606#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000607 if (need_synchronize_access) {
608 // We explicitly ask for no rights other than synchronization.
609 // This gives us the best chance of succeeding.
610 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
611 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100612 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000613 return false;
614 }
615 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000616 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000617#elif defined(WEBRTC_POSIX)
618 thread_ = pthread_self();
619#endif
620 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000621 thread_manager->SetCurrentThread(this);
622 return true;
623}
624
Tommi51492422017-12-04 15:18:23 +0100625bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +0100626#if defined(WEBRTC_WIN)
627 return thread_ != nullptr;
628#elif defined(WEBRTC_POSIX)
629 return thread_ != 0;
630#endif
631}
632
Steve Antonbcc1a762019-12-11 11:21:53 -0800633// static
634MessageHandler* Thread::GetPostTaskMessageHandler() {
635 // Allocate at first call, never deallocate.
636 static MessageHandler* handler = new MessageHandlerWithTask;
637 return handler;
638}
639
Taylor Brandstetter08672602018-03-02 15:20:33 -0800640AutoThread::AutoThread()
641 : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000642 if (!ThreadManager::Instance()->CurrentThread()) {
Niels Möller5a8f8602019-06-12 11:30:59 +0200643 // DoInit registers with MessageQueueManager. Do that only if we intend to
644 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
645 // post a message to a queue that no running thread is serving.
646 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000647 ThreadManager::Instance()->SetCurrentThread(this);
648 }
649}
650
651AutoThread::~AutoThread() {
652 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700653 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000654 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800655 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000656 }
657}
658
nisse7eaa4ea2017-05-08 05:25:41 -0700659AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800660 : Thread(ss, /*do_init=*/false) {
661 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -0700662 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100663 // Temporarily set the current thread to nullptr so that we can keep checks
664 // around that catch unintentional pointer overwrites.
665 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700666 rtc::ThreadManager::Instance()->SetCurrentThread(this);
667 if (old_thread_) {
668 MessageQueueManager::Remove(old_thread_);
669 }
670}
671
672AutoSocketServerThread::~AutoSocketServerThread() {
673 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
674 // Some tests post destroy messages to this thread. To avoid memory
675 // leaks, we have to process those messages. In particular
676 // P2PTransportChannelPingTest, relying on the message posted in
677 // cricket::Connection::Destroy.
678 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -0700679 // Stop and destroy the thread before clearing it as the current thread.
680 // Sometimes there are messages left in the MessageQueue that will be
681 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
682 // its contents rely on this thread still being set as the current thread.
683 Stop();
684 DoDestroy();
Tommi51492422017-12-04 15:18:23 +0100685 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700686 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
687 if (old_thread_) {
688 MessageQueueManager::Add(old_thread_);
689 }
690}
691
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000692} // namespace rtc