PlatformThread: add support for detached threads.

The change introduces support for detachable PlatformThreads, for which
the Stop() call doesn't wait until the thread has finished executing.

The change also introduces rtc::ThreadAttributes that carries priority
and detachability thread attributes. It additionally refactors all
known use to use the new semantics.

Bug: b:181572711, webrtc:12659
Change-Id: Id96e87c2a0dafabc8047767d241fd5da4505d14c
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/214704
Reviewed-by: Tommi <tommi@webrtc.org>
Reviewed-by: Harald Alvestrand <hta@webrtc.org>
Commit-Queue: Markus Handell <handellm@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#33796}
diff --git a/rtc_base/platform_thread.cc b/rtc_base/platform_thread.cc
index 8a5f2c9..c5f3bc3 100644
--- a/rtc_base/platform_thread.cc
+++ b/rtc_base/platform_thread.cc
@@ -10,6 +10,8 @@
 
 #include "rtc_base/platform_thread.h"
 
+#include <memory>
+
 #if !defined(WEBRTC_WIN)
 #include <sched.h>
 #endif
@@ -18,123 +20,22 @@
 
 #include <algorithm>
 
+#include "absl/memory/memory.h"
 #include "rtc_base/checks.h"
 
 namespace rtc {
+
 namespace {
-#if !defined(WEBRTC_WIN)
-struct ThreadAttributes {
-  ThreadAttributes() { pthread_attr_init(&attr); }
-  ~ThreadAttributes() { pthread_attr_destroy(&attr); }
-  pthread_attr_t* operator&() { return &attr; }
-  pthread_attr_t attr;
+struct ThreadStartData {
+  ThreadRunFunction run_function;
+  void* obj;
+  std::string thread_name;
+  ThreadPriority priority;
 };
-#endif  // defined(WEBRTC_WIN)
-}  // namespace
 
-PlatformThread::PlatformThread(ThreadRunFunction func,
-                               void* obj,
-                               absl::string_view thread_name,
-                               ThreadPriority priority /*= kNormalPriority*/)
-    : run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
-  RTC_DCHECK(func);
-  RTC_DCHECK(!name_.empty());
-  // TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
-  RTC_DCHECK(name_.length() < 64);
-  spawned_thread_checker_.Detach();
-}
-
-PlatformThread::~PlatformThread() {
-  RTC_DCHECK(thread_checker_.IsCurrent());
+bool SetPriority(ThreadPriority priority) {
 #if defined(WEBRTC_WIN)
-  RTC_DCHECK(!thread_);
-  RTC_DCHECK(!thread_id_);
-#endif  // defined(WEBRTC_WIN)
-}
-
-#if defined(WEBRTC_WIN)
-DWORD WINAPI PlatformThread::StartThread(void* param) {
-  // The GetLastError() function only returns valid results when it is called
-  // after a Win32 API function that returns a "failed" result. A crash dump
-  // contains the result from GetLastError() and to make sure it does not
-  // falsely report a Windows error we call SetLastError here.
-  ::SetLastError(ERROR_SUCCESS);
-  static_cast<PlatformThread*>(param)->Run();
-  return 0;
-}
-#else
-void* PlatformThread::StartThread(void* param) {
-  static_cast<PlatformThread*>(param)->Run();
-  return 0;
-}
-#endif  // defined(WEBRTC_WIN)
-
-void PlatformThread::Start() {
-  RTC_DCHECK(thread_checker_.IsCurrent());
-  RTC_DCHECK(!thread_) << "Thread already started?";
-#if defined(WEBRTC_WIN)
-  // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
-  // Set the reserved stack stack size to 1M, which is the default on Windows
-  // and Linux.
-  thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
-                           STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
-  RTC_CHECK(thread_) << "CreateThread failed";
-  RTC_DCHECK(thread_id_);
-#else
-  ThreadAttributes attr;
-  // Set the stack stack size to 1M.
-  pthread_attr_setstacksize(&attr, 1024 * 1024);
-  RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
-#endif  // defined(WEBRTC_WIN)
-}
-
-bool PlatformThread::IsRunning() const {
-  RTC_DCHECK(thread_checker_.IsCurrent());
-#if defined(WEBRTC_WIN)
-  return thread_ != nullptr;
-#else
-  return thread_ != 0;
-#endif  // defined(WEBRTC_WIN)
-}
-
-PlatformThreadRef PlatformThread::GetThreadRef() const {
-#if defined(WEBRTC_WIN)
-  return thread_id_;
-#else
-  return thread_;
-#endif  // defined(WEBRTC_WIN)
-}
-
-void PlatformThread::Stop() {
-  RTC_DCHECK(thread_checker_.IsCurrent());
-  if (!IsRunning())
-    return;
-
-#if defined(WEBRTC_WIN)
-  WaitForSingleObject(thread_, INFINITE);
-  CloseHandle(thread_);
-  thread_ = nullptr;
-  thread_id_ = 0;
-#else
-  RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
-  thread_ = 0;
-#endif  // defined(WEBRTC_WIN)
-  spawned_thread_checker_.Detach();
-}
-
-void PlatformThread::Run() {
-  // Attach the worker thread checker to this thread.
-  RTC_DCHECK(spawned_thread_checker_.IsCurrent());
-  rtc::SetCurrentThreadName(name_.c_str());
-  SetPriority(priority_);
-  run_function_(obj_);
-}
-
-bool PlatformThread::SetPriority(ThreadPriority priority) {
-  RTC_DCHECK(spawned_thread_checker_.IsCurrent());
-
-#if defined(WEBRTC_WIN)
-  return SetThreadPriority(thread_, priority) != FALSE;
+  return SetThreadPriority(GetCurrentThread(), priority) != FALSE;
 #elif defined(__native_client__) || defined(WEBRTC_FUCHSIA)
   // Setting thread priorities is not supported in NaCl or Fuchsia.
   return true;
@@ -176,13 +77,124 @@
       param.sched_priority = top_prio;
       break;
   }
-  return pthread_setschedparam(thread_, policy, &param) == 0;
+  return pthread_setschedparam(pthread_self(), policy, &param) == 0;
+#endif  // defined(WEBRTC_WIN)
+}
+
+void RunPlatformThread(std::unique_ptr<ThreadStartData> data) {
+  rtc::SetCurrentThreadName(data->thread_name.c_str());
+  data->thread_name.clear();
+  SetPriority(data->priority);
+  data->run_function(data->obj);
+}
+
+#if defined(WEBRTC_WIN)
+DWORD WINAPI StartThread(void* param) {
+  // The GetLastError() function only returns valid results when it is called
+  // after a Win32 API function that returns a "failed" result. A crash dump
+  // contains the result from GetLastError() and to make sure it does not
+  // falsely report a Windows error we call SetLastError here.
+  ::SetLastError(ERROR_SUCCESS);
+  RunPlatformThread(absl::WrapUnique(static_cast<ThreadStartData*>(param)));
+  return 0;
+}
+#else
+void* StartThread(void* param) {
+  RunPlatformThread(absl::WrapUnique(static_cast<ThreadStartData*>(param)));
+  return 0;
+}
+#endif  // defined(WEBRTC_WIN)
+
+}  // namespace
+
+PlatformThread::PlatformThread(ThreadRunFunction func,
+                               void* obj,
+                               absl::string_view thread_name,
+                               ThreadAttributes attributes)
+    : run_function_(func),
+      attributes_(attributes),
+      obj_(obj),
+      name_(thread_name) {
+  RTC_DCHECK(func);
+  RTC_DCHECK(!name_.empty());
+  // TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
+  RTC_DCHECK(name_.length() < 64);
+}
+
+PlatformThread::~PlatformThread() {
+  RTC_DCHECK_RUN_ON(&thread_checker_);
+  RTC_DCHECK(!thread_);
+#if defined(WEBRTC_WIN)
+  RTC_DCHECK(!thread_id_);
+#endif  // defined(WEBRTC_WIN)
+}
+
+void PlatformThread::Start() {
+  RTC_DCHECK_RUN_ON(&thread_checker_);
+  RTC_DCHECK(!thread_) << "Thread already started?";
+  ThreadStartData* data =
+      new ThreadStartData{run_function_, obj_, name_, attributes_.priority};
+#if defined(WEBRTC_WIN)
+  // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
+  // Set the reserved stack stack size to 1M, which is the default on Windows
+  // and Linux.
+  thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, data,
+                           STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
+  RTC_CHECK(thread_) << "CreateThread failed";
+  RTC_DCHECK(thread_id_);
+#else
+  pthread_attr_t attr;
+  pthread_attr_init(&attr);
+  // Set the stack stack size to 1M.
+  pthread_attr_setstacksize(&attr, 1024 * 1024);
+  pthread_attr_setdetachstate(&attr, attributes_.joinable
+                                         ? PTHREAD_CREATE_JOINABLE
+                                         : PTHREAD_CREATE_DETACHED);
+  RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, data));
+  pthread_attr_destroy(&attr);
+#endif  // defined(WEBRTC_WIN)
+}
+
+bool PlatformThread::IsRunning() const {
+  RTC_DCHECK_RUN_ON(&thread_checker_);
+#if defined(WEBRTC_WIN)
+  return thread_ != nullptr;
+#else
+  return thread_ != 0;
+#endif  // defined(WEBRTC_WIN)
+}
+
+PlatformThreadRef PlatformThread::GetThreadRef() const {
+#if defined(WEBRTC_WIN)
+  return thread_id_;
+#else
+  return thread_;
+#endif  // defined(WEBRTC_WIN)
+}
+
+void PlatformThread::Stop() {
+  RTC_DCHECK_RUN_ON(&thread_checker_);
+  if (!IsRunning())
+    return;
+
+#if defined(WEBRTC_WIN)
+  if (attributes_.joinable) {
+    WaitForSingleObject(thread_, INFINITE);
+  }
+  CloseHandle(thread_);
+  thread_ = nullptr;
+  thread_id_ = 0;
+#else
+  if (attributes_.joinable) {
+    RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
+  }
+  thread_ = 0;
 #endif  // defined(WEBRTC_WIN)
 }
 
 #if defined(WEBRTC_WIN)
 bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
-  RTC_DCHECK(thread_checker_.IsCurrent());
+  RTC_DCHECK_RUN_ON(&thread_checker_);
   RTC_DCHECK(IsRunning());
 
   return QueueUserAPC(function, thread_, data) != FALSE;