xref: /aosp_15_r20/external/webrtc/rtc_base/platform_thread.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2015 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 
11 #include "rtc_base/platform_thread.h"
12 
13 #include <algorithm>
14 #include <memory>
15 
16 #if !defined(WEBRTC_WIN)
17 #include <sched.h>
18 #endif
19 
20 #include "rtc_base/checks.h"
21 
22 namespace rtc {
23 namespace {
24 
25 #if defined(WEBRTC_WIN)
Win32PriorityFromThreadPriority(ThreadPriority priority)26 int Win32PriorityFromThreadPriority(ThreadPriority priority) {
27   switch (priority) {
28     case ThreadPriority::kLow:
29       return THREAD_PRIORITY_BELOW_NORMAL;
30     case ThreadPriority::kNormal:
31       return THREAD_PRIORITY_NORMAL;
32     case ThreadPriority::kHigh:
33       return THREAD_PRIORITY_ABOVE_NORMAL;
34     case ThreadPriority::kRealtime:
35       return THREAD_PRIORITY_TIME_CRITICAL;
36   }
37 }
38 #endif
39 
SetPriority(ThreadPriority priority)40 bool SetPriority(ThreadPriority priority) {
41 #if defined(WEBRTC_WIN)
42   return SetThreadPriority(GetCurrentThread(),
43                            Win32PriorityFromThreadPriority(priority)) != FALSE;
44 #elif defined(__native_client__) || defined(WEBRTC_FUCHSIA)
45   // Setting thread priorities is not supported in NaCl or Fuchsia.
46   return true;
47 #elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
48   // TODO(tommi): Switch to the same mechanism as Chromium uses for changing
49   // thread priorities.
50   return true;
51 #else
52   const int policy = SCHED_FIFO;
53   const int min_prio = sched_get_priority_min(policy);
54   const int max_prio = sched_get_priority_max(policy);
55   if (min_prio == -1 || max_prio == -1) {
56     return false;
57   }
58 
59   if (max_prio - min_prio <= 2)
60     return false;
61 
62   // Convert webrtc priority to system priorities:
63   sched_param param;
64   const int top_prio = max_prio - 1;
65   const int low_prio = min_prio + 1;
66   switch (priority) {
67     case ThreadPriority::kLow:
68       param.sched_priority = low_prio;
69       break;
70     case ThreadPriority::kNormal:
71       // The -1 ensures that the kHighPriority is always greater or equal to
72       // kNormalPriority.
73       param.sched_priority = (low_prio + top_prio - 1) / 2;
74       break;
75     case ThreadPriority::kHigh:
76       param.sched_priority = std::max(top_prio - 2, low_prio);
77       break;
78     case ThreadPriority::kRealtime:
79       param.sched_priority = top_prio;
80       break;
81   }
82   return pthread_setschedparam(pthread_self(), policy, &param) == 0;
83 #endif  // defined(WEBRTC_WIN)
84 }
85 
86 #if defined(WEBRTC_WIN)
RunPlatformThread(void * param)87 DWORD WINAPI RunPlatformThread(void* param) {
88   // The GetLastError() function only returns valid results when it is called
89   // after a Win32 API function that returns a "failed" result. A crash dump
90   // contains the result from GetLastError() and to make sure it does not
91   // falsely report a Windows error we call SetLastError here.
92   ::SetLastError(ERROR_SUCCESS);
93   auto function = static_cast<std::function<void()>*>(param);
94   (*function)();
95   delete function;
96   return 0;
97 }
98 #else
RunPlatformThread(void * param)99 void* RunPlatformThread(void* param) {
100   auto function = static_cast<std::function<void()>*>(param);
101   (*function)();
102   delete function;
103   return 0;
104 }
105 #endif  // defined(WEBRTC_WIN)
106 
107 }  // namespace
108 
PlatformThread(Handle handle,bool joinable)109 PlatformThread::PlatformThread(Handle handle, bool joinable)
110     : handle_(handle), joinable_(joinable) {}
111 
PlatformThread(PlatformThread && rhs)112 PlatformThread::PlatformThread(PlatformThread&& rhs)
113     : handle_(rhs.handle_), joinable_(rhs.joinable_) {
114   rhs.handle_ = absl::nullopt;
115 }
116 
operator =(PlatformThread && rhs)117 PlatformThread& PlatformThread::operator=(PlatformThread&& rhs) {
118   Finalize();
119   handle_ = rhs.handle_;
120   joinable_ = rhs.joinable_;
121   rhs.handle_ = absl::nullopt;
122   return *this;
123 }
124 
~PlatformThread()125 PlatformThread::~PlatformThread() {
126   Finalize();
127 }
128 
SpawnJoinable(std::function<void ()> thread_function,absl::string_view name,ThreadAttributes attributes)129 PlatformThread PlatformThread::SpawnJoinable(
130     std::function<void()> thread_function,
131     absl::string_view name,
132     ThreadAttributes attributes) {
133   return SpawnThread(std::move(thread_function), name, attributes,
134                      /*joinable=*/true);
135 }
136 
SpawnDetached(std::function<void ()> thread_function,absl::string_view name,ThreadAttributes attributes)137 PlatformThread PlatformThread::SpawnDetached(
138     std::function<void()> thread_function,
139     absl::string_view name,
140     ThreadAttributes attributes) {
141   return SpawnThread(std::move(thread_function), name, attributes,
142                      /*joinable=*/false);
143 }
144 
GetHandle() const145 absl::optional<PlatformThread::Handle> PlatformThread::GetHandle() const {
146   return handle_;
147 }
148 
149 #if defined(WEBRTC_WIN)
QueueAPC(PAPCFUNC function,ULONG_PTR data)150 bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
151   RTC_DCHECK(handle_.has_value());
152   return handle_.has_value() ? QueueUserAPC(function, *handle_, data) != FALSE
153                              : false;
154 }
155 #endif
156 
Finalize()157 void PlatformThread::Finalize() {
158   if (!handle_.has_value())
159     return;
160 #if defined(WEBRTC_WIN)
161   if (joinable_)
162     WaitForSingleObject(*handle_, INFINITE);
163   CloseHandle(*handle_);
164 #else
165   if (joinable_)
166     RTC_CHECK_EQ(0, pthread_join(*handle_, nullptr));
167 #endif
168   handle_ = absl::nullopt;
169 }
170 
SpawnThread(std::function<void ()> thread_function,absl::string_view name,ThreadAttributes attributes,bool joinable)171 PlatformThread PlatformThread::SpawnThread(
172     std::function<void()> thread_function,
173     absl::string_view name,
174     ThreadAttributes attributes,
175     bool joinable) {
176   RTC_DCHECK(thread_function);
177   RTC_DCHECK(!name.empty());
178   // TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
179   RTC_DCHECK(name.length() < 64);
180   auto start_thread_function_ptr =
181       new std::function<void()>([thread_function = std::move(thread_function),
182                                  name = std::string(name), attributes] {
183         rtc::SetCurrentThreadName(name.c_str());
184         SetPriority(attributes.priority);
185         thread_function();
186       });
187 #if defined(WEBRTC_WIN)
188   // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
189   // Set the reserved stack stack size to 1M, which is the default on Windows
190   // and Linux.
191   DWORD thread_id = 0;
192   PlatformThread::Handle handle = ::CreateThread(
193       nullptr, 1024 * 1024, &RunPlatformThread, start_thread_function_ptr,
194       STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id);
195   RTC_CHECK(handle) << "CreateThread failed";
196 #else
197   pthread_attr_t attr;
198   pthread_attr_init(&attr);
199   // Set the stack stack size to 1M.
200   pthread_attr_setstacksize(&attr, 1024 * 1024);
201   pthread_attr_setdetachstate(
202       &attr, joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED);
203   PlatformThread::Handle handle;
204   RTC_CHECK_EQ(0, pthread_create(&handle, &attr, &RunPlatformThread,
205                                  start_thread_function_ptr));
206   pthread_attr_destroy(&attr);
207 #endif  // defined(WEBRTC_WIN)
208   return PlatformThread(handle, joinable);
209 }
210 
211 }  // namespace rtc
212