You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

621 lines
17 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #include "rtc_base/thread.h"
  11. #if defined(WEBRTC_WIN)
  12. #include <comdef.h>
  13. #elif defined(WEBRTC_POSIX)
  14. #include <time.h>
  15. #else
  16. #error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
  17. #endif
  18. #if defined(WEBRTC_WIN)
  19. // Disable warning that we don't care about:
  20. // warning C4722: destructor never returns, potential memory leak
  21. #pragma warning(disable : 4722)
  22. #endif
  23. #include <stdio.h>
  24. #include <utility>
  25. #include "rtc_base/checks.h"
  26. #include "rtc_base/critical_section.h"
  27. #include "rtc_base/logging.h"
  28. #include "rtc_base/null_socket_server.h"
  29. #include "rtc_base/time_utils.h"
  30. #include "rtc_base/trace_event.h"
  31. #if defined(WEBRTC_MAC)
  32. #include "rtc_base/system/cocoa_threading.h"
  33. /*
  34. * These are forward-declarations for methods that are part of the
  35. * ObjC runtime. They are declared in the private header objc-internal.h.
  36. * These calls are what clang inserts when using @autoreleasepool in ObjC,
  37. * but here they are used directly in order to keep this file C++.
  38. * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
  39. */
  40. extern "C" {
  41. void* objc_autoreleasePoolPush(void);
  42. void objc_autoreleasePoolPop(void* pool);
  43. }
  44. namespace {
  45. class ScopedAutoReleasePool {
  46. public:
  47. ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
  48. ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
  49. private:
  50. void* const pool_;
  51. };
  52. } // namespace
  53. #endif
  54. namespace rtc {
  55. ThreadManager* ThreadManager::Instance() {
  56. static ThreadManager* const thread_manager = new ThreadManager();
  57. return thread_manager;
  58. }
  59. ThreadManager::~ThreadManager() {
  60. // By above RTC_DEFINE_STATIC_LOCAL.
  61. RTC_NOTREACHED() << "ThreadManager should never be destructed.";
  62. }
  63. // static
  64. Thread* Thread::Current() {
  65. ThreadManager* manager = ThreadManager::Instance();
  66. Thread* thread = manager->CurrentThread();
  67. #ifndef NO_MAIN_THREAD_WRAPPING
  68. // Only autowrap the thread which instantiated the ThreadManager.
  69. if (!thread && manager->IsMainThread()) {
  70. thread = new Thread(SocketServer::CreateDefault());
  71. thread->WrapCurrentWithThreadManager(manager, true);
  72. }
  73. #endif
  74. return thread;
  75. }
  76. #if defined(WEBRTC_POSIX)
  77. ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
  78. #if defined(WEBRTC_MAC)
  79. InitCocoaMultiThreading();
  80. #endif
  81. pthread_key_create(&key_, nullptr);
  82. }
  83. Thread* ThreadManager::CurrentThread() {
  84. return static_cast<Thread*>(pthread_getspecific(key_));
  85. }
  86. void ThreadManager::SetCurrentThread(Thread* thread) {
  87. #if RTC_DLOG_IS_ON
  88. if (CurrentThread() && thread) {
  89. RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
  90. }
  91. #endif // RTC_DLOG_IS_ON
  92. pthread_setspecific(key_, thread);
  93. }
  94. #endif
  95. #if defined(WEBRTC_WIN)
  96. ThreadManager::ThreadManager()
  97. : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
  98. Thread* ThreadManager::CurrentThread() {
  99. return static_cast<Thread*>(TlsGetValue(key_));
  100. }
  101. void ThreadManager::SetCurrentThread(Thread* thread) {
  102. RTC_DCHECK(!CurrentThread() || !thread);
  103. TlsSetValue(key_, thread);
  104. }
  105. #endif
  106. Thread* ThreadManager::WrapCurrentThread() {
  107. Thread* result = CurrentThread();
  108. if (nullptr == result) {
  109. result = new Thread(SocketServer::CreateDefault());
  110. result->WrapCurrentWithThreadManager(this, true);
  111. }
  112. return result;
  113. }
  114. void ThreadManager::UnwrapCurrentThread() {
  115. Thread* t = CurrentThread();
  116. if (t && !(t->IsOwned())) {
  117. t->UnwrapCurrent();
  118. delete t;
  119. }
  120. }
  121. bool ThreadManager::IsMainThread() {
  122. return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
  123. }
  124. Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
  125. : thread_(Thread::Current()),
  126. previous_state_(thread_->SetAllowBlockingCalls(false)) {}
  127. Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
  128. RTC_DCHECK(thread_->IsCurrent());
  129. thread_->SetAllowBlockingCalls(previous_state_);
  130. }
  131. Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
  132. Thread::Thread(std::unique_ptr<SocketServer> ss)
  133. : Thread(std::move(ss), /*do_init=*/true) {}
  134. Thread::Thread(SocketServer* ss, bool do_init)
  135. : MessageQueue(ss, /*do_init=*/false) {
  136. SetName("Thread", this); // default name
  137. if (do_init) {
  138. DoInit();
  139. }
  140. }
  141. Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
  142. : MessageQueue(std::move(ss), false) {
  143. SetName("Thread", this); // default name
  144. if (do_init) {
  145. DoInit();
  146. }
  147. }
  148. Thread::~Thread() {
  149. Stop();
  150. DoDestroy();
  151. }
  152. bool Thread::IsCurrent() const {
  153. return ThreadManager::Instance()->CurrentThread() == this;
  154. }
  155. std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
  156. return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
  157. }
  158. std::unique_ptr<Thread> Thread::Create() {
  159. return std::unique_ptr<Thread>(
  160. new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
  161. }
  162. bool Thread::SleepMs(int milliseconds) {
  163. AssertBlockingIsAllowedOnCurrentThread();
  164. #if defined(WEBRTC_WIN)
  165. ::Sleep(milliseconds);
  166. return true;
  167. #else
  168. // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
  169. // so we use nanosleep() even though it has greater precision than necessary.
  170. struct timespec ts;
  171. ts.tv_sec = milliseconds / 1000;
  172. ts.tv_nsec = (milliseconds % 1000) * 1000000;
  173. int ret = nanosleep(&ts, nullptr);
  174. if (ret != 0) {
  175. RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
  176. return false;
  177. }
  178. return true;
  179. #endif
  180. }
  181. bool Thread::SetName(const std::string& name, const void* obj) {
  182. RTC_DCHECK(!IsRunning());
  183. name_ = name;
  184. if (obj) {
  185. // The %p specifier typically produce at most 16 hex digits, possibly with a
  186. // 0x prefix. But format is implementation defined, so add some margin.
  187. char buf[30];
  188. snprintf(buf, sizeof(buf), " 0x%p", obj);
  189. name_ += buf;
  190. }
  191. return true;
  192. }
  193. bool Thread::Start() {
  194. RTC_DCHECK(!IsRunning());
  195. if (IsRunning())
  196. return false;
  197. Restart(); // reset IsQuitting() if the thread is being restarted
  198. // Make sure that ThreadManager is created on the main thread before
  199. // we start a new thread.
  200. ThreadManager::Instance();
  201. owned_ = true;
  202. #if defined(WEBRTC_WIN)
  203. thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
  204. if (!thread_) {
  205. return false;
  206. }
  207. #elif defined(WEBRTC_POSIX)
  208. pthread_attr_t attr;
  209. pthread_attr_init(&attr);
  210. int error_code = pthread_create(&thread_, &attr, PreRun, this);
  211. if (0 != error_code) {
  212. RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
  213. thread_ = 0;
  214. return false;
  215. }
  216. RTC_DCHECK(thread_);
  217. #endif
  218. return true;
  219. }
  220. bool Thread::WrapCurrent() {
  221. return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
  222. }
  223. void Thread::UnwrapCurrent() {
  224. // Clears the platform-specific thread-specific storage.
  225. ThreadManager::Instance()->SetCurrentThread(nullptr);
  226. #if defined(WEBRTC_WIN)
  227. if (thread_ != nullptr) {
  228. if (!CloseHandle(thread_)) {
  229. RTC_LOG_GLE(LS_ERROR)
  230. << "When unwrapping thread, failed to close handle.";
  231. }
  232. thread_ = nullptr;
  233. thread_id_ = 0;
  234. }
  235. #elif defined(WEBRTC_POSIX)
  236. thread_ = 0;
  237. #endif
  238. }
  239. void Thread::SafeWrapCurrent() {
  240. WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
  241. }
  242. void Thread::Join() {
  243. if (!IsRunning())
  244. return;
  245. RTC_DCHECK(!IsCurrent());
  246. if (Current() && !Current()->blocking_calls_allowed_) {
  247. RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
  248. << "but blocking calls have been disallowed";
  249. }
  250. #if defined(WEBRTC_WIN)
  251. RTC_DCHECK(thread_ != nullptr);
  252. WaitForSingleObject(thread_, INFINITE);
  253. CloseHandle(thread_);
  254. thread_ = nullptr;
  255. thread_id_ = 0;
  256. #elif defined(WEBRTC_POSIX)
  257. pthread_join(thread_, nullptr);
  258. thread_ = 0;
  259. #endif
  260. }
  261. bool Thread::SetAllowBlockingCalls(bool allow) {
  262. RTC_DCHECK(IsCurrent());
  263. bool previous = blocking_calls_allowed_;
  264. blocking_calls_allowed_ = allow;
  265. return previous;
  266. }
  267. // static
  268. void Thread::AssertBlockingIsAllowedOnCurrentThread() {
  269. #if !defined(NDEBUG)
  270. Thread* current = Thread::Current();
  271. RTC_DCHECK(!current || current->blocking_calls_allowed_);
  272. #endif
  273. }
  274. // static
  275. #if defined(WEBRTC_WIN)
  276. DWORD WINAPI Thread::PreRun(LPVOID pv) {
  277. #else
  278. void* Thread::PreRun(void* pv) {
  279. #endif
  280. Thread* thread = static_cast<Thread*>(pv);
  281. ThreadManager::Instance()->SetCurrentThread(thread);
  282. rtc::SetCurrentThreadName(thread->name_.c_str());
  283. #if defined(WEBRTC_MAC)
  284. ScopedAutoReleasePool pool;
  285. #endif
  286. thread->Run();
  287. ThreadManager::Instance()->SetCurrentThread(nullptr);
  288. #ifdef WEBRTC_WIN
  289. return 0;
  290. #else
  291. return nullptr;
  292. #endif
  293. } // namespace rtc
  294. void Thread::Run() {
  295. ProcessMessages(kForever);
  296. }
  297. bool Thread::IsOwned() {
  298. RTC_DCHECK(IsRunning());
  299. return owned_;
  300. }
  301. void Thread::Stop() {
  302. MessageQueue::Quit();
  303. Join();
  304. }
  305. void Thread::Send(const Location& posted_from,
  306. MessageHandler* phandler,
  307. uint32_t id,
  308. MessageData* pdata) {
  309. if (IsQuitting())
  310. return;
  311. // Sent messages are sent to the MessageHandler directly, in the context
  312. // of "thread", like Win32 SendMessage. If in the right context,
  313. // call the handler directly.
  314. Message msg;
  315. msg.posted_from = posted_from;
  316. msg.phandler = phandler;
  317. msg.message_id = id;
  318. msg.pdata = pdata;
  319. if (IsCurrent()) {
  320. phandler->OnMessage(&msg);
  321. return;
  322. }
  323. AssertBlockingIsAllowedOnCurrentThread();
  324. AutoThread thread;
  325. Thread* current_thread = Thread::Current();
  326. RTC_DCHECK(current_thread != nullptr); // AutoThread ensures this
  327. bool ready = false;
  328. {
  329. CritScope cs(&crit_);
  330. _SendMessage smsg;
  331. smsg.thread = current_thread;
  332. smsg.msg = msg;
  333. smsg.ready = &ready;
  334. sendlist_.push_back(smsg);
  335. }
  336. // Wait for a reply
  337. WakeUpSocketServer();
  338. bool waited = false;
  339. crit_.Enter();
  340. while (!ready) {
  341. crit_.Leave();
  342. // We need to limit "ReceiveSends" to |this| thread to avoid an arbitrary
  343. // thread invoking calls on the current thread.
  344. current_thread->ReceiveSendsFromThread(this);
  345. current_thread->socketserver()->Wait(kForever, false);
  346. waited = true;
  347. crit_.Enter();
  348. }
  349. crit_.Leave();
  350. // Our Wait loop above may have consumed some WakeUp events for this
  351. // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
  352. // cause problems for some SocketServers.
  353. //
  354. // Concrete example:
  355. // Win32SocketServer on thread A calls Send on thread B. While processing the
  356. // message, thread B Posts a message to A. We consume the wakeup for that
  357. // Post while waiting for the Send to complete, which means that when we exit
  358. // this loop, we need to issue another WakeUp, or else the Posted message
  359. // won't be processed in a timely manner.
  360. if (waited) {
  361. current_thread->socketserver()->WakeUp();
  362. }
  363. }
  364. void Thread::ReceiveSends() {
  365. ReceiveSendsFromThread(nullptr);
  366. }
  367. void Thread::ReceiveSendsFromThread(const Thread* source) {
  368. // Receive a sent message. Cleanup scenarios:
  369. // - thread sending exits: We don't allow this, since thread can exit
  370. // only via Join, so Send must complete.
  371. // - thread receiving exits: Wakeup/set ready in Thread::Clear()
  372. // - object target cleared: Wakeup/set ready in Thread::Clear()
  373. _SendMessage smsg;
  374. crit_.Enter();
  375. while (PopSendMessageFromThread(source, &smsg)) {
  376. crit_.Leave();
  377. Dispatch(&smsg.msg);
  378. crit_.Enter();
  379. *smsg.ready = true;
  380. smsg.thread->socketserver()->WakeUp();
  381. }
  382. crit_.Leave();
  383. }
  384. bool Thread::PopSendMessageFromThread(const Thread* source, _SendMessage* msg) {
  385. for (std::list<_SendMessage>::iterator it = sendlist_.begin();
  386. it != sendlist_.end(); ++it) {
  387. if (it->thread == source || source == nullptr) {
  388. *msg = *it;
  389. sendlist_.erase(it);
  390. return true;
  391. }
  392. }
  393. return false;
  394. }
  395. void Thread::InvokeInternal(const Location& posted_from,
  396. MessageHandler* handler) {
  397. TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",
  398. posted_from.file_and_line(), "src_func",
  399. posted_from.function_name());
  400. Send(posted_from, handler);
  401. }
  402. bool Thread::IsProcessingMessagesForTesting() {
  403. return (owned_ || IsCurrent()) &&
  404. MessageQueue::IsProcessingMessagesForTesting();
  405. }
  406. void Thread::Clear(MessageHandler* phandler,
  407. uint32_t id,
  408. MessageList* removed) {
  409. CritScope cs(&crit_);
  410. // Remove messages on sendlist_ with phandler
  411. // Object target cleared: remove from send list, wakeup/set ready
  412. // if sender not null.
  413. std::list<_SendMessage>::iterator iter = sendlist_.begin();
  414. while (iter != sendlist_.end()) {
  415. _SendMessage smsg = *iter;
  416. if (smsg.msg.Match(phandler, id)) {
  417. if (removed) {
  418. removed->push_back(smsg.msg);
  419. } else {
  420. delete smsg.msg.pdata;
  421. }
  422. iter = sendlist_.erase(iter);
  423. *smsg.ready = true;
  424. smsg.thread->socketserver()->WakeUp();
  425. continue;
  426. }
  427. ++iter;
  428. }
  429. ClearInternal(phandler, id, removed);
  430. }
  431. bool Thread::ProcessMessages(int cmsLoop) {
  432. // Using ProcessMessages with a custom clock for testing and a time greater
  433. // than 0 doesn't work, since it's not guaranteed to advance the custom
  434. // clock's time, and may get stuck in an infinite loop.
  435. RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
  436. cmsLoop == kForever);
  437. int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
  438. int cmsNext = cmsLoop;
  439. while (true) {
  440. #if defined(WEBRTC_MAC)
  441. ScopedAutoReleasePool pool;
  442. #endif
  443. Message msg;
  444. if (!Get(&msg, cmsNext))
  445. return !IsQuitting();
  446. Dispatch(&msg);
  447. if (cmsLoop != kForever) {
  448. cmsNext = static_cast<int>(TimeUntil(msEnd));
  449. if (cmsNext < 0)
  450. return true;
  451. }
  452. }
  453. }
  454. bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
  455. bool need_synchronize_access) {
  456. RTC_DCHECK(!IsRunning());
  457. #if defined(WEBRTC_WIN)
  458. if (need_synchronize_access) {
  459. // We explicitly ask for no rights other than synchronization.
  460. // This gives us the best chance of succeeding.
  461. thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
  462. if (!thread_) {
  463. RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
  464. return false;
  465. }
  466. thread_id_ = GetCurrentThreadId();
  467. }
  468. #elif defined(WEBRTC_POSIX)
  469. thread_ = pthread_self();
  470. #endif
  471. owned_ = false;
  472. thread_manager->SetCurrentThread(this);
  473. return true;
  474. }
  475. bool Thread::IsRunning() {
  476. #if defined(WEBRTC_WIN)
  477. return thread_ != nullptr;
  478. #elif defined(WEBRTC_POSIX)
  479. return thread_ != 0;
  480. #endif
  481. }
  482. AutoThread::AutoThread()
  483. : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
  484. if (!ThreadManager::Instance()->CurrentThread()) {
  485. // DoInit registers with MessageQueueManager. Do that only if we intend to
  486. // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
  487. // post a message to a queue that no running thread is serving.
  488. DoInit();
  489. ThreadManager::Instance()->SetCurrentThread(this);
  490. }
  491. }
  492. AutoThread::~AutoThread() {
  493. Stop();
  494. DoDestroy();
  495. if (ThreadManager::Instance()->CurrentThread() == this) {
  496. ThreadManager::Instance()->SetCurrentThread(nullptr);
  497. }
  498. }
  499. AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
  500. : Thread(ss, /*do_init=*/false) {
  501. DoInit();
  502. old_thread_ = ThreadManager::Instance()->CurrentThread();
  503. // Temporarily set the current thread to nullptr so that we can keep checks
  504. // around that catch unintentional pointer overwrites.
  505. rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
  506. rtc::ThreadManager::Instance()->SetCurrentThread(this);
  507. if (old_thread_) {
  508. MessageQueueManager::Remove(old_thread_);
  509. }
  510. }
  511. AutoSocketServerThread::~AutoSocketServerThread() {
  512. RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
  513. // Some tests post destroy messages to this thread. To avoid memory
  514. // leaks, we have to process those messages. In particular
  515. // P2PTransportChannelPingTest, relying on the message posted in
  516. // cricket::Connection::Destroy.
  517. ProcessMessages(0);
  518. // Stop and destroy the thread before clearing it as the current thread.
  519. // Sometimes there are messages left in the MessageQueue that will be
  520. // destroyed by DoDestroy, and sometimes the destructors of the message and/or
  521. // its contents rely on this thread still being set as the current thread.
  522. Stop();
  523. DoDestroy();
  524. rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
  525. rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
  526. if (old_thread_) {
  527. MessageQueueManager::Add(old_thread_);
  528. }
  529. }
  530. } // namespace rtc