Allow overwriting current thread in ThreadManager.

This prepares for introducing a simulated time rtc::ThreadManager
implementation that will run on a single underlying thread.

Bug: webrtc:11255
Change-Id: I793128cc0b8e649a3675914de67dfee3298b446a
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/165765
Commit-Queue: Sebastian Jansson <srte@webrtc.org>
Reviewed-by: Steve Anton <steveanton@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#30256}
diff --git a/rtc_base/thread.cc b/rtc_base/thread.cc
index 6c5830f..a8e89cd 100644
--- a/rtc_base/thread.cc
+++ b/rtc_base/thread.cc
@@ -237,12 +237,7 @@
   return static_cast<Thread*>(pthread_getspecific(key_));
 }
 
-void ThreadManager::SetCurrentThread(Thread* thread) {
-#if RTC_DLOG_IS_ON
-  if (CurrentThread() && thread) {
-    RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
-  }
-#endif  // RTC_DLOG_IS_ON
+void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
   pthread_setspecific(key_, thread);
 }
 #endif
@@ -255,12 +250,24 @@
   return static_cast<Thread*>(TlsGetValue(key_));
 }
 
-void ThreadManager::SetCurrentThread(Thread* thread) {
-  RTC_DCHECK(!CurrentThread() || !thread);
+void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
   TlsSetValue(key_, thread);
 }
 #endif
 
+void ThreadManager::SetCurrentThread(Thread* thread) {
+#if RTC_DLOG_IS_ON
+  if (CurrentThread() && thread) {
+    RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
+  }
+#endif  // RTC_DLOG_IS_ON
+  SetCurrentThreadInternal(thread);
+}
+
+void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
+  SetCurrentThreadInternal(thread);
+}
+
 Thread* ThreadManager::WrapCurrentThread() {
   Thread* result = CurrentThread();
   if (nullptr == result) {
diff --git a/rtc_base/thread.h b/rtc_base/thread.h
index b8af583..f8b41d1 100644
--- a/rtc_base/thread.h
+++ b/rtc_base/thread.h
@@ -90,6 +90,9 @@
 
   Thread* CurrentThread();
   void SetCurrentThread(Thread* thread);
+  // Allows changing the current thread, this is intended for tests where we
+  // want to simulate multiple threads running on a single physical thread.
+  void ChangeCurrentThreadForTest(Thread* thread);
 
   // Returns a thread object with its thread_ ivar set
   // to whatever the OS uses to represent the thread.
@@ -113,6 +116,7 @@
   ThreadManager();
   ~ThreadManager();
 
+  void SetCurrentThreadInternal(Thread* thread);
   void AddInternal(Thread* message_queue);
   void RemoveInternal(Thread* message_queue);
   void ClearInternal(MessageHandler* handler);