blob: 20f58b2c819455abbc1b01b40dc090f19882e117 [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());
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200338#if defined(WEBRTC_MAC)
339 ScopedAutoReleasePool pool;
340#endif
Niels Möllerd2e50132019-06-11 09:24:14 +0200341 thread->Run();
342
Tommi51492422017-12-04 15:18:23 +0100343 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgasonde6adbe2017-02-22 00:42:11 -0800344#ifdef WEBRTC_WIN
345 return 0;
346#else
347 return nullptr;
348#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200349} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350
351void Thread::Run() {
352 ProcessMessages(kForever);
353}
354
355bool Thread::IsOwned() {
Tommi51492422017-12-04 15:18:23 +0100356 RTC_DCHECK(IsRunning());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000357 return owned_;
358}
359
360void Thread::Stop() {
361 MessageQueue::Quit();
362 Join();
363}
364
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700365void Thread::Send(const Location& posted_from,
366 MessageHandler* phandler,
367 uint32_t id,
368 MessageData* pdata) {
André Susano Pinto02a57972016-07-22 13:30:05 +0200369 if (IsQuitting())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370 return;
371
372 // Sent messages are sent to the MessageHandler directly, in the context
373 // of "thread", like Win32 SendMessage. If in the right context,
374 // call the handler directly.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375 Message msg;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700376 msg.posted_from = posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000377 msg.phandler = phandler;
378 msg.message_id = id;
379 msg.pdata = pdata;
380 if (IsCurrent()) {
381 phandler->OnMessage(&msg);
382 return;
383 }
384
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000385 AssertBlockingIsAllowedOnCurrentThread();
386
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000387 AutoThread thread;
Yves Gerey665174f2018-06-19 15:03:05 +0200388 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800389 RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000390
391 bool ready = false;
392 {
393 CritScope cs(&crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000394 _SendMessage smsg;
395 smsg.thread = current_thread;
396 smsg.msg = msg;
397 smsg.ready = &ready;
398 sendlist_.push_back(smsg);
399 }
400
401 // Wait for a reply
jbauch9ccedc32016-02-25 01:14:56 -0800402 WakeUpSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000403
404 bool waited = false;
405 crit_.Enter();
406 while (!ready) {
407 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000408 // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
409 // thread invoking calls on the current thread.
410 current_thread->ReceiveSendsFromThread(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000411 current_thread->socketserver()->Wait(kForever, false);
412 waited = true;
413 crit_.Enter();
414 }
415 crit_.Leave();
416
417 // Our Wait loop above may have consumed some WakeUp events for this
418 // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
419 // cause problems for some SocketServers.
420 //
421 // Concrete example:
422 // Win32SocketServer on thread A calls Send on thread B. While processing the
423 // message, thread B Posts a message to A. We consume the wakeup for that
424 // Post while waiting for the Send to complete, which means that when we exit
425 // this loop, we need to issue another WakeUp, or else the Posted message
426 // won't be processed in a timely manner.
427
428 if (waited) {
429 current_thread->socketserver()->WakeUp();
430 }
431}
432
433void Thread::ReceiveSends() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800434 ReceiveSendsFromThread(nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000435}
436
437void Thread::ReceiveSendsFromThread(const Thread* source) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000438 // Receive a sent message. Cleanup scenarios:
439 // - thread sending exits: We don't allow this, since thread can exit
440 // only via Join, so Send must complete.
441 // - thread receiving exits: Wakeup/set ready in Thread::Clear()
442 // - object target cleared: Wakeup/set ready in Thread::Clear()
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000443 _SendMessage smsg;
444
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000445 crit_.Enter();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000446 while (PopSendMessageFromThread(source, &smsg)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447 crit_.Leave();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000448
Ishan Khota3b66012018-06-26 20:04:43 -0700449 Dispatch(&smsg.msg);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000450
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000451 crit_.Enter();
452 *smsg.ready = true;
453 smsg.thread->socketserver()->WakeUp();
454 }
455 crit_.Leave();
456}
457
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000458bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
459 for (std::list<_SendMessage>::iterator it = sendlist_.begin();
460 it != sendlist_.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800461 if (it->thread == source || source == nullptr) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000462 *msg = *it;
463 sendlist_.erase(it);
464 return true;
465 }
466 }
467 return false;
468}
469
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700470void Thread::InvokeInternal(const Location& posted_from,
471 MessageHandler* handler) {
472 TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
473 posted_from.file_and_line(), "src_func",
474 posted_from.function_name());
475 Send(posted_from, handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000476}
477
Niels Möller8909a632018-09-06 08:42:44 +0200478bool Thread::IsProcessingMessagesForTesting() {
479 return (owned_ || IsCurrent()) &&
480 MessageQueue::IsProcessingMessagesForTesting();
481}
482
Peter Boström0c4e06b2015-10-07 12:23:21 +0200483void Thread::Clear(MessageHandler* phandler,
484 uint32_t id,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000485 MessageList* removed) {
486 CritScope cs(&crit_);
487
488 // Remove messages on sendlist_ with phandler
489 // Object target cleared: remove from send list, wakeup/set ready
deadbeef37f5ecf2017-02-27 14:06:41 -0800490 // if sender not null.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000491
492 std::list<_SendMessage>::iterator iter = sendlist_.begin();
493 while (iter != sendlist_.end()) {
494 _SendMessage smsg = *iter;
495 if (smsg.msg.Match(phandler, id)) {
496 if (removed) {
497 removed->push_back(smsg.msg);
498 } else {
499 delete smsg.msg.pdata;
500 }
501 iter = sendlist_.erase(iter);
502 *smsg.ready = true;
503 smsg.thread->socketserver()->WakeUp();
504 continue;
505 }
506 ++iter;
507 }
508
Niels Möller5e007b72018-09-07 12:35:44 +0200509 ClearInternal(phandler, id, removed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510}
511
512bool Thread::ProcessMessages(int cmsLoop) {
deadbeef22e08142017-06-12 14:30:28 -0700513 // Using ProcessMessages with a custom clock for testing and a time greater
514 // than 0 doesn't work, since it's not guaranteed to advance the custom
515 // clock's time, and may get stuck in an infinite loop.
516 RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
517 cmsLoop == kForever);
Honghai Zhang82d78622016-05-06 11:29:15 -0700518 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000519 int cmsNext = cmsLoop;
520
521 while (true) {
Kári Tristan Helgason62b13452018-10-12 12:57:49 +0200522#if defined(WEBRTC_MAC)
523 ScopedAutoReleasePool pool;
524#endif
kthelgasonde6adbe2017-02-22 00:42:11 -0800525 Message msg;
526 if (!Get(&msg, cmsNext))
527 return !IsQuitting();
528 Dispatch(&msg);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000529
kthelgasonde6adbe2017-02-22 00:42:11 -0800530 if (cmsLoop != kForever) {
531 cmsNext = static_cast<int>(TimeUntil(msEnd));
532 if (cmsNext < 0)
533 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000534 }
535 }
536}
537
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000538bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
539 bool need_synchronize_access) {
Tommi51492422017-12-04 15:18:23 +0100540 RTC_DCHECK(!IsRunning());
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000541
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000542#if defined(WEBRTC_WIN)
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000543 if (need_synchronize_access) {
544 // We explicitly ask for no rights other than synchronization.
545 // This gives us the best chance of succeeding.
546 thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
547 if (!thread_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100548 RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000549 return false;
550 }
551 thread_id_ = GetCurrentThreadId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000552 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000553#elif defined(WEBRTC_POSIX)
554 thread_ = pthread_self();
555#endif
556 owned_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000557 thread_manager->SetCurrentThread(this);
558 return true;
559}
560
Tommi51492422017-12-04 15:18:23 +0100561bool Thread::IsRunning() {
Tommi51492422017-12-04 15:18:23 +0100562#if defined(WEBRTC_WIN)
563 return thread_ != nullptr;
564#elif defined(WEBRTC_POSIX)
565 return thread_ != 0;
566#endif
567}
568
Taylor Brandstetter08672602018-03-02 15:20:33 -0800569AutoThread::AutoThread()
570 : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000571 if (!ThreadManager::Instance()->CurrentThread()) {
Niels Möller5a8f8602019-06-12 11:30:59 +0200572 // DoInit registers with MessageQueueManager. Do that only if we intend to
573 // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
574 // post a message to a queue that no running thread is serving.
575 DoInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000576 ThreadManager::Instance()->SetCurrentThread(this);
577 }
578}
579
580AutoThread::~AutoThread() {
581 Stop();
Steve Anton3b80aac2017-10-19 10:17:12 -0700582 DoDestroy();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000583 if (ThreadManager::Instance()->CurrentThread() == this) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800584 ThreadManager::Instance()->SetCurrentThread(nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000585 }
586}
587
nisse7eaa4ea2017-05-08 05:25:41 -0700588AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
Taylor Brandstetter08672602018-03-02 15:20:33 -0800589 : Thread(ss, /*do_init=*/false) {
590 DoInit();
nisse7eaa4ea2017-05-08 05:25:41 -0700591 old_thread_ = ThreadManager::Instance()->CurrentThread();
Tommi51492422017-12-04 15:18:23 +0100592 // Temporarily set the current thread to nullptr so that we can keep checks
593 // around that catch unintentional pointer overwrites.
594 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700595 rtc::ThreadManager::Instance()->SetCurrentThread(this);
596 if (old_thread_) {
597 MessageQueueManager::Remove(old_thread_);
598 }
599}
600
601AutoSocketServerThread::~AutoSocketServerThread() {
602 RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
603 // Some tests post destroy messages to this thread. To avoid memory
604 // leaks, we have to process those messages. In particular
605 // P2PTransportChannelPingTest, relying on the message posted in
606 // cricket::Connection::Destroy.
607 ProcessMessages(0);
Steve Anton3b80aac2017-10-19 10:17:12 -0700608 // Stop and destroy the thread before clearing it as the current thread.
609 // Sometimes there are messages left in the MessageQueue that will be
610 // destroyed by DoDestroy, and sometimes the destructors of the message and/or
611 // its contents rely on this thread still being set as the current thread.
612 Stop();
613 DoDestroy();
Tommi51492422017-12-04 15:18:23 +0100614 rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
nisse7eaa4ea2017-05-08 05:25:41 -0700615 rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
616 if (old_thread_) {
617 MessageQueueManager::Add(old_thread_);
618 }
619}
620
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000621} // namespace rtc