blob: 6d369d747e5bf5a16ea0ddf1bdedaf739d0b7f6a [file] [log] [blame]
Tommibebc6902015-05-18 09:51:42 +02001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/platform_thread.h"
Tommibebc6902015-05-18 09:51:42 +020012
Markus Handellad5037b2021-05-07 15:02:36 +020013#include <algorithm>
Markus Handell97c44582021-04-20 17:41:54 +020014#include <memory>
15
Yves Gerey988cc082018-10-23 12:03:01 +020016#if !defined(WEBRTC_WIN)
17#include <sched.h>
18#endif
Jonas Olssona4d87372019-07-05 19:08:33 +020019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
Tommibebc6902015-05-18 09:51:42 +020021
Tommibebc6902015-05-18 09:51:42 +020022namespace rtc {
Guido Urdaneta793bac52021-05-06 13:12:47 +000023namespace {
Markus Handellad5037b2021-05-07 15:02:36 +020024
25#if defined(WEBRTC_WIN)
26int 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
pbos12411ef2015-11-23 14:47:56 -080039
Markus Handell97c44582021-04-20 17:41:54 +020040bool SetPriority(ThreadPriority priority) {
pbos12411ef2015-11-23 14:47:56 -080041#if defined(WEBRTC_WIN)
Markus Handellad5037b2021-05-07 15:02:36 +020042 return SetThreadPriority(GetCurrentThread(),
43 Win32PriorityFromThreadPriority(priority)) != FALSE;
Wez0614ed92018-02-06 13:38:21 -080044#elif defined(__native_client__) || defined(WEBRTC_FUCHSIA)
45 // Setting thread priorities is not supported in NaCl or Fuchsia.
Peter Boströmc6612132015-11-24 18:10:24 +010046 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.
pbos12411ef2015-11-23 14:47:56 -080050 return true;
51#else
pbos12411ef2015-11-23 14:47:56 -080052 const int policy = SCHED_FIFO;
pbos12411ef2015-11-23 14:47:56 -080053 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
Peter Boström97c821d2015-11-24 13:48:13 +010062 // Convert webrtc priority to system priorities:
pbos12411ef2015-11-23 14:47:56 -080063 sched_param param;
Peter Boström97c821d2015-11-24 13:48:13 +010064 const int top_prio = max_prio - 1;
65 const int low_prio = min_prio + 1;
66 switch (priority) {
Markus Handellad5037b2021-05-07 15:02:36 +020067 case ThreadPriority::kLow:
Peter Boström97c821d2015-11-24 13:48:13 +010068 param.sched_priority = low_prio;
69 break;
Markus Handellad5037b2021-05-07 15:02:36 +020070 case ThreadPriority::kNormal:
Peter Boström97c821d2015-11-24 13:48:13 +010071 // 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;
Markus Handellad5037b2021-05-07 15:02:36 +020075 case ThreadPriority::kHigh:
Peter Boström97c821d2015-11-24 13:48:13 +010076 param.sched_priority = std::max(top_prio - 2, low_prio);
77 break;
Markus Handellad5037b2021-05-07 15:02:36 +020078 case ThreadPriority::kRealtime:
Peter Boström97c821d2015-11-24 13:48:13 +010079 param.sched_priority = top_prio;
80 break;
pbos12411ef2015-11-23 14:47:56 -080081 }
Markus Handell97c44582021-04-20 17:41:54 +020082 return pthread_setschedparam(pthread_self(), policy, &param) == 0;
83#endif // defined(WEBRTC_WIN)
84}
85
Markus Handell97c44582021-04-20 17:41:54 +020086#if defined(WEBRTC_WIN)
Markus Handellad5037b2021-05-07 15:02:36 +020087DWORD WINAPI RunPlatformThread(void* param) {
Markus Handell97c44582021-04-20 17:41:54 +020088 // 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);
Markus Handellad5037b2021-05-07 15:02:36 +020093 auto function = static_cast<std::function<void()>*>(param);
94 (*function)();
95 delete function;
Markus Handell97c44582021-04-20 17:41:54 +020096 return 0;
97}
98#else
Markus Handellad5037b2021-05-07 15:02:36 +020099void* RunPlatformThread(void* param) {
100 auto function = static_cast<std::function<void()>*>(param);
101 (*function)();
102 delete function;
Markus Handell97c44582021-04-20 17:41:54 +0200103 return 0;
104}
105#endif // defined(WEBRTC_WIN)
106
107} // namespace
108
Markus Handellad5037b2021-05-07 15:02:36 +0200109PlatformThread::PlatformThread(Handle handle, bool joinable)
110 : handle_(handle), joinable_(joinable) {}
111
112PlatformThread::PlatformThread(PlatformThread&& rhs)
113 : handle_(rhs.handle_), joinable_(rhs.joinable_) {
114 rhs.handle_ = absl::nullopt;
115}
116
117PlatformThread& PlatformThread::operator=(PlatformThread&& rhs) {
118 Finalize();
119 handle_ = rhs.handle_;
120 joinable_ = rhs.joinable_;
121 rhs.handle_ = absl::nullopt;
122 return *this;
Markus Handell97c44582021-04-20 17:41:54 +0200123}
124
125PlatformThread::~PlatformThread() {
Markus Handellad5037b2021-05-07 15:02:36 +0200126 Finalize();
Markus Handellc89fdd72021-05-05 10:42:04 +0200127}
128
Markus Handellad5037b2021-05-07 15:02:36 +0200129PlatformThread 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
137PlatformThread 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
145absl::optional<PlatformThread::Handle> PlatformThread::GetHandle() const {
146 return handle_;
147}
148
149#if defined(WEBRTC_WIN)
150bool 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
157void 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
171PlatformThread 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 });
Markus Handell97c44582021-04-20 17:41:54 +0200187#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.
Markus Handellad5037b2021-05-07 15:02:36 +0200191 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";
Markus Handell97c44582021-04-20 17:41:54 +0200196#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);
Markus Handellad5037b2021-05-07 15:02:36 +0200201 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));
Markus Handell97c44582021-04-20 17:41:54 +0200206 pthread_attr_destroy(&attr);
207#endif // defined(WEBRTC_WIN)
Markus Handellad5037b2021-05-07 15:02:36 +0200208 return PlatformThread(handle, joinable);
Markus Handell97c44582021-04-20 17:41:54 +0200209}
210
Peter Boström8c38e8b2015-11-26 17:45:47 +0100211} // namespace rtc