blob: 90be69588544de782456fb8ea2b13ed55a6e6f4a [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 {
66
67ThreadManager* ThreadManager::Instance() {
Niels Möller14682a32018-05-24 08:54:25 +020068 static ThreadManager* const thread_manager = new ThreadManager();
69 return thread_manager;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070}
71
nisse7866cfe2017-04-26 01:45:31 -070072ThreadManager::~ThreadManager() {
73 // By above RTC_DEFINE_STATIC_LOCAL.
74 RTC_NOTREACHED() << "ThreadManager should never be destructed.";
75}
76
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000077// static
78Thread* Thread::Current() {
nisse7866cfe2017-04-26 01:45:31 -070079 ThreadManager* manager = ThreadManager::Instance();
80 Thread* thread = manager->CurrentThread();
81
Niels Moller9d1840c2019-05-21 07:26:37 +000082#ifndef NO_MAIN_THREAD_WRAPPING
83 // Only autowrap the thread which instantiated the ThreadManager.
84 if (!thread && manager->IsMainThread()) {
85 thread = new Thread(SocketServer::CreateDefault());
86 thread->WrapCurrentWithThreadManager(manager, true);
87 }
88#endif
89
nisse7866cfe2017-04-26 01:45:31 -070090 return thread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091}
92
93#if defined(WEBRTC_POSIX)
Niels Moller9d1840c2019-05-21 07:26:37 +000094ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +020095#if defined(WEBRTC_MAC)
96 InitCocoaMultiThreading();
97#endif
deadbeef37f5ecf2017-02-27 14:06:41 -080098 pthread_key_create(&key_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000099}
100
Yves Gerey665174f2018-06-19 15:03:05 +0200101Thread* ThreadManager::CurrentThread() {
102 return static_cast<Thread*>(pthread_getspecific(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103}
104
Tommi6f314bb2017-12-04 20:38:20 +0100105void ThreadManager::SetCurrentThread(Thread* thread) {
106#if RTC_DLOG_IS_ON
107 if (CurrentThread() && thread) {
108 RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
109 }
110#endif // RTC_DLOG_IS_ON
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 pthread_setspecific(key_, thread);
112}
113#endif
114
115#if defined(WEBRTC_WIN)
Niels Moller9d1840c2019-05-21 07:26:37 +0000116ThreadManager::ThreadManager()
117 : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200118
119Thread* ThreadManager::CurrentThread() {
120 return static_cast<Thread*>(TlsGetValue(key_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121}
122
Yves Gerey665174f2018-06-19 15:03:05 +0200123void ThreadManager::SetCurrentThread(Thread* thread) {
Tommi51492422017-12-04 15:18:23 +0100124 RTC_DCHECK(!CurrentThread() || !thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125 TlsSetValue(key_, thread);
126}
127#endif
128
Yves Gerey665174f2018-06-19 15:03:05 +0200129Thread* ThreadManager::WrapCurrentThread() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000130 Thread* result = CurrentThread();
deadbeef37f5ecf2017-02-27 14:06:41 -0800131 if (nullptr == result) {
tommie7251592017-07-14 14:44:46 -0700132 result = new Thread(SocketServer::CreateDefault());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000133 result->WrapCurrentWithThreadManager(this, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134 }
135 return result;
136}
137
138void ThreadManager::UnwrapCurrentThread() {
139 Thread* t = CurrentThread();
140 if (t && !(t->IsOwned())) {
141 t->UnwrapCurrent();
142 delete t;
143 }
144}
145
Niels Moller9d1840c2019-05-21 07:26:37 +0000146bool ThreadManager::IsMainThread() {
147 return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
148}
149
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000150Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
Yves Gerey665174f2018-06-19 15:03:05 +0200151 : thread_(Thread::Current()),
152 previous_state_(thread_->SetAllowBlockingCalls(false)) {}
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000153
154Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
nisseede5da42017-01-12 05:15:36 -0800155 RTC_DCHECK(thread_->IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000156 thread_->SetAllowBlockingCalls(previous_state_);
157}
158
Taylor Brandstetter08672602018-03-02 15:20:33 -0800159Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
danilchapbebf54c2016-04-28 01:32:48 -0700160
161Thread::Thread(std::unique_ptr<SocketServer> ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800162 : Thread(std::move(ss), /*do_init=*/true) {}
163
164Thread::Thread(SocketServer* ss, bool do_init)
165 : MessageQueue(ss, /*do_init=*/false) {
166 SetName("Thread", this); // default name
167 if (do_init) {
168 DoInit();
169 }
170}
171
172Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
Tommi51492422017-12-04 15:18:23 +0100173 : MessageQueue(std::move(ss), false) {
danilchapbebf54c2016-04-28 01:32:48 -0700174 SetName("Thread", this); // default name
Taylor Brandstetter08672602018-03-02 15:20:33 -0800175 if (do_init) {
176 DoInit();
177 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178}
179
180Thread::~Thread() {
181 Stop();
jbauch25d1f282016-02-05 00:25:02 -0800182 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000183}
184
nisse7866cfe2017-04-26 01:45:31 -0700185bool Thread::IsCurrent() const {
186 return ThreadManager::Instance()->CurrentThread() == this;
187}
188
danilchapbebf54c2016-04-28 01:32:48 -0700189std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
190 return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
191}
192
193std::unique_ptr<Thread> Thread::Create() {
194 return std::unique_ptr<Thread>(
195 new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
196}
197
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198bool Thread::SleepMs(int milliseconds) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000199 AssertBlockingIsAllowedOnCurrentThread();
200
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000201#if defined(WEBRTC_WIN)
202 ::Sleep(milliseconds);
203 return true;
204#else
205 // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
206 // so we use nanosleep() even though it has greater precision than necessary.
207 struct timespec ts;
208 ts.tv_sec = milliseconds / 1000;
209 ts.tv_nsec = (milliseconds % 1000) * 1000000;
deadbeef37f5ecf2017-02-27 14:06:41 -0800210 int ret = nanosleep(&ts, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000211 if (ret != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100212 RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213 return false;
214 }
215 return true;
216#endif
217}
218
219bool Thread::SetName(const std::string& name, const void* obj) {
Tommi51492422017-12-04 15:18:23 +0100220 RTC_DCHECK(!IsRunning());
221
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222 name_ = name;
223 if (obj) {
Niels Mölleraba06332018-10-16 15:14:15 +0200224 // The %p specifier typically produce at most 16 hex digits, possibly with a
225 // 0x prefix. But format is implementation defined, so add some margin.
226 char buf[30];
227 snprintf(buf, sizeof(buf), " 0x%p", obj);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000228 name_ += buf;
229 }
230 return true;
231}
232
Niels Möllerd2e50132019-06-11 09:24:14 +0200233bool Thread::Start() {
Tommi51492422017-12-04 15:18:23 +0100234 RTC_DCHECK(!IsRunning());
235
236 if (IsRunning())
237 return false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000238
André Susano Pinto02a57972016-07-22 13:30:05 +0200239 Restart(); // reset IsQuitting() if the thread is being restarted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240
241 // Make sure that ThreadManager is created on the main thread before
242 // we start a new thread.
243 ThreadManager::Instance();
244
Tommi51492422017-12-04 15:18:23 +0100245 owned_ = true;
246
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247#if defined(WEBRTC_WIN)
Niels Möllerd2e50132019-06-11 09:24:14 +0200248 thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
Tommi51492422017-12-04 15:18:23 +0100249 if (!thread_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250 return false;
251 }
252#elif defined(WEBRTC_POSIX)
253 pthread_attr_t attr;
254 pthread_attr_init(&attr);
255
Niels Möllerd2e50132019-06-11 09:24:14 +0200256 int error_code = pthread_create(&thread_, &attr, PreRun, this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000257 if (0 != error_code) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100258 RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
Tommi51492422017-12-04 15:18:23 +0100259 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260 return false;
261 }
Tommi51492422017-12-04 15:18:23 +0100262 RTC_DCHECK(thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263#endif
264 return true;
265}
266
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000267bool Thread::WrapCurrent() {
268 return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
269}
270
271void Thread::UnwrapCurrent() {
272 // Clears the platform-specific thread-specific storage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800273 ThreadManager::Instance()->SetCurrentThread(nullptr);
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000274#if defined(WEBRTC_WIN)
deadbeef37f5ecf2017-02-27 14:06:41 -0800275 if (thread_ != nullptr) {
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000276 if (!CloseHandle(thread_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100277 RTC_LOG_GLE(LS_ERROR)
278 << "When unwrapping thread, failed to close handle.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000279 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800280 thread_ = nullptr;
Tommi51492422017-12-04 15:18:23 +0100281 thread_id_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000282 }
Tommi51492422017-12-04 15:18:23 +0100283#elif defined(WEBRTC_POSIX)
284 thread_ = 0;
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000285#endif
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000286}
287
288void Thread::SafeWrapCurrent() {
289 WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
290}
291
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292void Thread::Join() {
Tommi51492422017-12-04 15:18:23 +0100293 if (!IsRunning())
294 return;
295
296 RTC_DCHECK(!IsCurrent());
297 if (Current() && !Current()->blocking_calls_allowed_) {
298 RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
299 << "but blocking calls have been disallowed";
300 }
jiayl@webrtc.org1fd362c2014-09-26 16:57:07 +0000301
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100303 RTC_DCHECK(thread_ != nullptr);
304 WaitForSingleObject(thread_, INFINITE);
305 CloseHandle(thread_);
306 thread_ = nullptr;
307 thread_id_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308#elif defined(WEBRTC_POSIX)
Tommi51492422017-12-04 15:18:23 +0100309 pthread_join(thread_, nullptr);
310 thread_ = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000312}
313
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000314bool Thread::SetAllowBlockingCalls(bool allow) {
nisseede5da42017-01-12 05:15:36 -0800315 RTC_DCHECK(IsCurrent());
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000316 bool previous = blocking_calls_allowed_;
317 blocking_calls_allowed_ = allow;
318 return previous;
319}
320
321// static
322void Thread::AssertBlockingIsAllowedOnCurrentThread() {
tfarinaa41ab932015-10-30 16:08:48 -0700323#if !defined(NDEBUG)
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000324 Thread* current = Thread::Current();
nisseede5da42017-01-12 05:15:36 -0800325 RTC_DCHECK(!current || current->blocking_calls_allowed_);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000326#endif
327}
328
deadbeefdc20e262017-01-31 15:10:44 -0800329// static
330#if defined(WEBRTC_WIN)
331DWORD WINAPI Thread::PreRun(LPVOID pv) {
332#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000333void* Thread::PreRun(void* pv) {
deadbeefdc20e262017-01-31 15:10:44 -0800334#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200335 Thread* thread = static_cast<Thread*>(pv);
336 ThreadManager::Instance()->SetCurrentThread(thread);
337 rtc::SetCurrentThreadName(thread->name_.c_str());
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100338 CurrentTaskQueueSetter set_current_task_queue(thread);
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200339#if defined(WEBRTC_MAC)
340 ScopedAutoReleasePool pool;
341#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200342 thread->Run();
343
Tommi51492422017-12-04 15:18:23 +0100344 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800345#ifdef WEBRTC_WIN
346 return 0;
347#else
348 return nullptr;
349#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200350} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351
352void Thread::Run() {
353 ProcessMessages(kForever);
354}
355
356bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100357 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000358 return owned_;
359}
360
361void Thread::Stop() {
362 MessageQueue::Quit();
363 Join();
364}
365
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700366void Thread::Send(const Location& posted_from,
367 MessageHandler* phandler,
368 uint32_t id,
369 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200370 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000371 return;
372
373 // Sent messages are sent to the MessageHandler directly, in the context
374 // of "thread", like Win32 SendMessage. If in the right context,
375 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000376 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700377 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000378 msg.phandler = phandler;
379 msg.message_id = id;
380 msg.pdata = pdata;
381 if (IsCurrent()) {
382 phandler->OnMessage(&msg);
383 return;
384 }
385
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000386 AssertBlockingIsAllowedOnCurrentThread();
387
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000388 AutoThread thread;
Yves Gerey665174f2018-06-19 15:03:05 +0200389 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800390 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000391
392 bool ready = false;
393 {
394 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000395 _SendMessage smsg;
396 smsg.thread = current_thread;
397 smsg.msg = msg;
398 smsg.ready = &ready;
399 sendlist_.push_back(smsg);
400 }
401
402 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800403 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000404
405 bool waited = false;
406 crit_.Enter();
407 while (!ready) {
408 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000409 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
410 // thread invoking calls on the current thread.
411 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 current_thread->socketserver()->Wait(kForever, false);
413 waited = true;
414 crit_.Enter();
415 }
416 crit_.Leave();
417
418 // Our Wait loop above may have consumed some WakeUp events for this
419 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
420 // cause problems for some SocketServers.
421 //
422 // Concrete example:
423 // Win32SocketServer on thread A calls Send on thread B. While processing the
424 // message, thread B Posts a message to A. We consume the wakeup for that
425 // Post while waiting for the Send to complete, which means that when we exit
426 // this loop, we need to issue another WakeUp, or else the Posted message
427 // won't be processed in a timely manner.
428
429 if (waited) {
430 current_thread->socketserver()->WakeUp();
431 }
432}
433
434void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800435 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000436}
437
438void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000439 // Receive a sent message. Cleanup scenarios:
440 // - thread sending exits: We don't allow this, since thread can exit
441 // only via Join, so Send must complete.
442 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
443 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000444 _SendMessage smsg;
445
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000446 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000447 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000448 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000449
Ishan Khota3b66012018-06-26 20:04:43 -0700450 Dispatch(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000451
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000452 crit_.Enter();
453 *smsg.ready = true;
454 smsg.thread->socketserver()->WakeUp();
455 }
456 crit_.Leave();
457}
458
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000459bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
460 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
461 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800462 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000463 *msg = *it;
464 sendlist_.erase(it);
465 return true;
466 }
467 }
468 return false;
469}
470
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700471void Thread::InvokeInternal(const Location& posted_from,
Danil Chapovalov89313452019-11-29 12:56:43 +0100472 rtc::FunctionView<void()> functor) {
Steve Antonc5d7c522019-12-03 10:14:05 -0800473 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
474 "src_func", posted_from.function_name());
Danil Chapovalov89313452019-11-29 12:56:43 +0100475
476 class FunctorMessageHandler : public MessageHandler {
477 public:
478 explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
479 : functor_(functor) {}
480 void OnMessage(Message* msg) override { functor_(); }
481
482 private:
483 rtc::FunctionView<void()> functor_;
484 } handler(functor);
485
486 Send(posted_from, &handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000487}
488
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100489void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
490 RTC_DCHECK(msg);
491 auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
492 std::unique_ptr<webrtc::QueuedTask> task = std::move(data->data());
493 // MessageQueue expects handler to own Message::pdata when OnMessage is called
494 // Since MessageData is no longer needed, delete it.
495 delete data;
496
497 // QueuedTask interface uses Run return value to communicate who owns the
498 // task. false means QueuedTask took the ownership.
499 if (!task->Run())
500 task.release();
501}
502
503void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
504 // Though Post takes MessageData by raw pointer (last parameter), it still
505 // takes it with ownership.
506 Post(RTC_FROM_HERE, &queued_task_handler_,
507 /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
508}
509
510void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
511 uint32_t milliseconds) {
512 // Though PostDelayed takes MessageData by raw pointer (last parameter),
513 // it still takes it with ownership.
514 PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
515 /*id=*/0,
516 new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
517}
518
519void Thread::Delete() {
520 Stop();
521 delete this;
522}
523
Niels Möller8909a632018-09-06 08:42:44 +0200524bool Thread::IsProcessingMessagesForTesting() {
525 return (owned_ || IsCurrent()) &&
526 MessageQueue::IsProcessingMessagesForTesting();
527}
528
Peter Boström0c4e06b2015-10-07 12:23:21 +0200529void Thread::Clear(MessageHandler* phandler,
530 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000531 MessageList* removed) {
532 CritScope cs(&crit_);
533
534 // Remove messages on sendlist_ with phandler
535 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800536 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000537
538 std::list<_SendMessage>::iterator iter = sendlist_.begin();
539 while (iter != sendlist_.end()) {
540 _SendMessage smsg = *iter;
541 if (smsg.msg.Match(phandler, id)) {
542 if (removed) {
543 removed->push_back(smsg.msg);
544 } else {
545 delete smsg.msg.pdata;
546 }
547 iter = sendlist_.erase(iter);
548 *smsg.ready = true;
549 smsg.thread->socketserver()->WakeUp();
550 continue;
551 }
552 ++iter;
553 }
554
Niels Möller5e007b72018-09-07 12:35:44 +0200555 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000556}
557
558bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700559 // Using ProcessMessages with a custom clock for testing and a time greater
560 // than 0 doesn't work, since it's not guaranteed to advance the custom
561 // clock's time, and may get stuck in an infinite loop.
562 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
563 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700564 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000565 int cmsNext = cmsLoop;
566
567 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200568#if defined(WEBRTC_MAC)
569 ScopedAutoReleasePool pool;
570#endif
kthelgasonde6adbe2017-02-22 00:42:11 -0800571 Message msg;
572 if (!Get(&msg, cmsNext))
573 return !IsQuitting();
574 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000575
kthelgasonde6adbe2017-02-22 00:42:11 -0800576 if (cmsLoop != kForever) {
577 cmsNext = static_cast<int>(TimeUntil(msEnd));
578 if (cmsNext < 0)
579 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000580 }
581 }
582}
583
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000584bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
585 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100586 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000587
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000588#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000589 if (need_synchronize_access) {
590 // We explicitly ask for no rights other than synchronization.
591 // This gives us the best chance of succeeding.
592 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
593 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100594 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000595 return false;
596 }
597 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000598 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000599#elif defined(WEBRTC_POSIX)
600 thread_ = pthread_self();
601#endif
602 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000603 thread_manager->SetCurrentThread(this);
604 return true;
605}
606
Tommi51492422017-12-04 15:18:23 +0100607bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +0100608#if defined(WEBRTC_WIN)
609 return thread_ != nullptr;
610#elif defined(WEBRTC_POSIX)
611 return thread_ != 0;
612#endif
613}
614
Taylor Brandstetter08672602018-03-02 15:20:33 -0800615AutoThread::AutoThread()
616 : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000617 if (!ThreadManager::Instance()->CurrentThread()) {
Niels Möller5a8f8602019-06-12 11:30:59 +0200618 // DoInit registers with MessageQueueManager. Do that only if we intend to
619 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
620 // post a message to a queue that no running thread is serving.
621 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000622 ThreadManager::Instance()->SetCurrentThread(this);
623 }
624}
625
626AutoThread::~AutoThread() {
627 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700628 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000629 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800630 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000631 }
632}
633
nisse7eaa4ea2017-05-08 05:25:41 -0700634AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800635 : Thread(ss, /*do_init=*/false) {
636 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -0700637 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100638 // Temporarily set the current thread to nullptr so that we can keep checks
639 // around that catch unintentional pointer overwrites.
640 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700641 rtc::ThreadManager::Instance()->SetCurrentThread(this);
642 if (old_thread_) {
643 MessageQueueManager::Remove(old_thread_);
644 }
645}
646
647AutoSocketServerThread::~AutoSocketServerThread() {
648 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
649 // Some tests post destroy messages to this thread. To avoid memory
650 // leaks, we have to process those messages. In particular
651 // P2PTransportChannelPingTest, relying on the message posted in
652 // cricket::Connection::Destroy.
653 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -0700654 // Stop and destroy the thread before clearing it as the current thread.
655 // Sometimes there are messages left in the MessageQueue that will be
656 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
657 // its contents rely on this thread still being set as the current thread.
658 Stop();
659 DoDestroy();
Tommi51492422017-12-04 15:18:23 +0100660 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700661 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
662 if (old_thread_) {
663 MessageQueueManager::Add(old_thread_);
664 }
665}
666
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000667} // namespace rtc