Fix flaky memory leak in RemoteAudioSource

Bug: webrtc:8405
Change-Id: Ie7c89214323678c6ea34e344bb1a5a33ad46b3f0
Reviewed-on: https://webrtc-review.googlesource.com/13401
Commit-Queue: Steve Anton <steveanton@webrtc.org>
Reviewed-by: Taylor Brandstetter <deadbeef@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#20362}
diff --git a/rtc_base/thread.cc b/rtc_base/thread.cc
index 1bc0c0c..41ba04e 100644
--- a/rtc_base/thread.cc
+++ b/rtc_base/thread.cc
@@ -529,6 +529,7 @@
 
 AutoThread::~AutoThread() {
   Stop();
+  DoDestroy();
   if (ThreadManager::Instance()->CurrentThread() == this) {
     ThreadManager::Instance()->SetCurrentThread(nullptr);
   }
@@ -550,6 +551,12 @@
   // P2PTransportChannelPingTest, relying on the message posted in
   // cricket::Connection::Destroy.
   ProcessMessages(0);
+  // Stop and destroy the thread before clearing it as the current thread.
+  // Sometimes there are messages left in the MessageQueue that will be
+  // destroyed by DoDestroy, and sometimes the destructors of the message and/or
+  // its contents rely on this thread still being set as the current thread.
+  Stop();
+  DoDestroy();
   rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
   if (old_thread_) {
     MessageQueueManager::Add(old_thread_);