blob: 63c8f6535124d6d0757b22a58d593f925385c5c4 [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
Yves Gerey988cc082018-10-23 12:03:01 +020013#if !defined(WEBRTC_WIN)
14#include <sched.h>
15#endif
16#include <stdint.h>
17#include <time.h>
18#include <algorithm>
19
Steve Anton10542f22019-01-11 09:11:00 -080020#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "rtc_base/time_utils.h"
Tommibebc6902015-05-18 09:51:42 +020023
Tommibebc6902015-05-18 09:51:42 +020024namespace rtc {
pbos12411ef2015-11-23 14:47:56 -080025namespace {
26#if defined(WEBRTC_WIN)
27void CALLBACK RaiseFlag(ULONG_PTR param) {
28 *reinterpret_cast<bool*>(param) = true;
29}
30#else
31struct ThreadAttributes {
32 ThreadAttributes() { pthread_attr_init(&attr); }
33 ~ThreadAttributes() { pthread_attr_destroy(&attr); }
34 pthread_attr_t* operator&() { return &attr; }
35 pthread_attr_t attr;
36};
pbos12411ef2015-11-23 14:47:56 -080037#endif // defined(WEBRTC_WIN)
38}
39
tommi0f8b4032017-02-22 11:22:05 -080040PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
pbos12411ef2015-11-23 14:47:56 -080041 void* obj,
Danil Chapovalov5a1a6db2019-01-17 19:55:46 +010042 absl::string_view thread_name)
43 : run_function_deprecated_(func), obj_(obj), name_(thread_name) {
pbos12411ef2015-11-23 14:47:56 -080044 RTC_DCHECK(func);
45 RTC_DCHECK(name_.length() < 64);
tommi0f8b4032017-02-22 11:22:05 -080046 spawned_thread_checker_.DetachFromThread();
47}
48
49PlatformThread::PlatformThread(ThreadRunFunction func,
50 void* obj,
Danil Chapovalov5a1a6db2019-01-17 19:55:46 +010051 absl::string_view thread_name,
tommi0f8b4032017-02-22 11:22:05 -080052 ThreadPriority priority /*= kNormalPriority*/)
53 : run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
54 RTC_DCHECK(func);
55 RTC_DCHECK(!name_.empty());
56 // TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
57 RTC_DCHECK(name_.length() < 64);
58 spawned_thread_checker_.DetachFromThread();
pbos12411ef2015-11-23 14:47:56 -080059}
60
61PlatformThread::~PlatformThread() {
62 RTC_DCHECK(thread_checker_.CalledOnValidThread());
63#if defined(WEBRTC_WIN)
64 RTC_DCHECK(!thread_);
tommi845afa82016-04-22 09:08:44 -070065 RTC_DCHECK(!thread_id_);
pbos12411ef2015-11-23 14:47:56 -080066#endif // defined(WEBRTC_WIN)
67}
68
69#if defined(WEBRTC_WIN)
70DWORD WINAPI PlatformThread::StartThread(void* param) {
perkj6a2e20a2016-11-30 04:53:08 -080071 // The GetLastError() function only returns valid results when it is called
72 // after a Win32 API function that returns a "failed" result. A crash dump
73 // contains the result from GetLastError() and to make sure it does not
74 // falsely report a Windows error we call SetLastError here.
75 ::SetLastError(ERROR_SUCCESS);
pbos12411ef2015-11-23 14:47:56 -080076 static_cast<PlatformThread*>(param)->Run();
77 return 0;
78}
79#else
80void* PlatformThread::StartThread(void* param) {
81 static_cast<PlatformThread*>(param)->Run();
82 return 0;
83}
84#endif // defined(WEBRTC_WIN)
85
Peter Boström8c38e8b2015-11-26 17:45:47 +010086void PlatformThread::Start() {
pbos12411ef2015-11-23 14:47:56 -080087 RTC_DCHECK(thread_checker_.CalledOnValidThread());
88 RTC_DCHECK(!thread_) << "Thread already started?";
89#if defined(WEBRTC_WIN)
90 stop_ = false;
91
92 // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
93 // Set the reserved stack stack size to 1M, which is the default on Windows
94 // and Linux.
deadbeef37f5ecf2017-02-27 14:06:41 -080095 thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
tommi845afa82016-04-22 09:08:44 -070096 STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
pbos12411ef2015-11-23 14:47:56 -080097 RTC_CHECK(thread_) << "CreateThread failed";
tommi845afa82016-04-22 09:08:44 -070098 RTC_DCHECK(thread_id_);
pbos12411ef2015-11-23 14:47:56 -080099#else
100 ThreadAttributes attr;
101 // Set the stack stack size to 1M.
102 pthread_attr_setstacksize(&attr, 1024 * 1024);
103 RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
104#endif // defined(WEBRTC_WIN)
pbos12411ef2015-11-23 14:47:56 -0800105}
106
Peter Boström8c38e8b2015-11-26 17:45:47 +0100107bool PlatformThread::IsRunning() const {
pbos12411ef2015-11-23 14:47:56 -0800108 RTC_DCHECK(thread_checker_.CalledOnValidThread());
109#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100110 return thread_ != nullptr;
pbos12411ef2015-11-23 14:47:56 -0800111#else
Peter Boström8c38e8b2015-11-26 17:45:47 +0100112 return thread_ != 0;
113#endif // defined(WEBRTC_WIN)
114}
pbos12411ef2015-11-23 14:47:56 -0800115
tommi845afa82016-04-22 09:08:44 -0700116PlatformThreadRef PlatformThread::GetThreadRef() const {
117#if defined(WEBRTC_WIN)
118 return thread_id_;
119#else
120 return thread_;
121#endif // defined(WEBRTC_WIN)
122}
123
Peter Boström8c38e8b2015-11-26 17:45:47 +0100124void PlatformThread::Stop() {
125 RTC_DCHECK(thread_checker_.CalledOnValidThread());
126 if (!IsRunning())
127 return;
128
129#if defined(WEBRTC_WIN)
130 // Set stop_ to |true| on the worker thread.
tommi845afa82016-04-22 09:08:44 -0700131 bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
Noah Richardsdbfb58b2019-04-02 16:18:57 -0700132 if (!queued) {
133 // Queuing the APC can fail if the thread is being terminated. This should
134 // return ERROR_GEN_FAILURE, though Wine returns ERROR_ACCESS_DENIED, so
135 // allow for either.
136 auto error = ::GetLastError();
137 if (error != ERROR_GEN_FAILURE && error != ERROR_ACCESS_DENIED) {
138 RTC_CHECK(false) << "Failed to QueueUserAPC, error: " << error;
139 }
140 }
Peter Boström8c38e8b2015-11-26 17:45:47 +0100141 WaitForSingleObject(thread_, INFINITE);
142 CloseHandle(thread_);
143 thread_ = nullptr;
tommi845afa82016-04-22 09:08:44 -0700144 thread_id_ = 0;
Peter Boström8c38e8b2015-11-26 17:45:47 +0100145#else
tommi0f8b4032017-02-22 11:22:05 -0800146 if (!run_function_)
147 RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800148 RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
tommi0f8b4032017-02-22 11:22:05 -0800149 if (!run_function_)
150 AtomicOps::ReleaseStore(&stop_flag_, 0);
pbos12411ef2015-11-23 14:47:56 -0800151 thread_ = 0;
152#endif // defined(WEBRTC_WIN)
tommi0f8b4032017-02-22 11:22:05 -0800153 spawned_thread_checker_.DetachFromThread();
pbos12411ef2015-11-23 14:47:56 -0800154}
155
tommi82ead602017-02-19 16:09:55 -0800156// TODO(tommi): Deprecate the loop behavior in PlatformThread.
157// * Introduce a new callback type that returns void.
158// * Remove potential for a busy loop in PlatformThread.
159// * Delegate the responsibility for how to stop the thread, to the
160// implementation that actually uses the thread.
161// All implementations will need to be aware of how the thread should be stopped
162// and encouraging a busy polling loop, can be costly in terms of power and cpu.
pbos12411ef2015-11-23 14:47:56 -0800163void PlatformThread::Run() {
tommi0f8b4032017-02-22 11:22:05 -0800164 // Attach the worker thread checker to this thread.
165 RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
166 rtc::SetCurrentThreadName(name_.c_str());
167
168 if (run_function_) {
169 SetPriority(priority_);
170 run_function_(obj_);
171 return;
172 }
tommi500f1b72017-03-02 07:07:09 -0800173
174// TODO(tommi): Delete the rest of this function when looping isn't supported.
175#if RTC_DCHECK_IS_ON
176 // These constants control the busy loop detection algorithm below.
177 // |kMaxLoopCount| controls the limit for how many times we allow the loop
178 // to run within a period, before DCHECKing.
179 // |kPeriodToMeasureMs| controls how long that period is.
180 static const int kMaxLoopCount = 1000;
181 static const int kPeriodToMeasureMs = 100;
182 int64_t loop_stamps[kMaxLoopCount] = {};
183 int64_t sequence_nr = 0;
danilchap27523472017-02-28 06:20:38 -0800184#endif
tommi500f1b72017-03-02 07:07:09 -0800185
pbos12411ef2015-11-23 14:47:56 -0800186 do {
sprange791ffd2016-01-26 01:53:20 -0800187 // The interface contract of Start/Stop is that for a successful call to
pbos12411ef2015-11-23 14:47:56 -0800188 // Start, there should be at least one call to the run function. So we
189 // call the function before checking |stop_|.
tommi0f8b4032017-02-22 11:22:05 -0800190 if (!run_function_deprecated_(obj_))
pbos12411ef2015-11-23 14:47:56 -0800191 break;
tommi500f1b72017-03-02 07:07:09 -0800192#if RTC_DCHECK_IS_ON
193 auto id = sequence_nr % kMaxLoopCount;
194 loop_stamps[id] = rtc::TimeMillis();
195 if (sequence_nr > kMaxLoopCount) {
196 auto compare_id = (id + 1) % kMaxLoopCount;
197 auto diff = loop_stamps[id] - loop_stamps[compare_id];
198 RTC_DCHECK_GE(diff, 0);
199 if (diff < kPeriodToMeasureMs) {
200 RTC_NOTREACHED() << "This thread is too busy: " << name_ << " " << diff
201 << "ms sequence=" << sequence_nr << " "
202 << loop_stamps[id] << " vs " << loop_stamps[compare_id]
203 << ", " << id << " vs " << compare_id;
204 }
205 }
206 ++sequence_nr;
207#endif
pbos12411ef2015-11-23 14:47:56 -0800208#if defined(WEBRTC_WIN)
209 // Alertable sleep to permit RaiseFlag to run and update |stop_|.
210 SleepEx(0, true);
211 } while (!stop_);
212#else
Yura Yaroshevich665d18e2018-01-23 17:10:29 +0300213#if defined(WEBRTC_MAC) || defined(WEBRTC_ANDROID)
tommi0473b1d2017-03-02 08:08:59 -0800214 sched_yield();
215#else
tommi500f1b72017-03-02 07:07:09 -0800216 static const struct timespec ts_null = {0};
danilchap27523472017-02-28 06:20:38 -0800217 nanosleep(&ts_null, nullptr);
218#endif
tommi82ead602017-02-19 16:09:55 -0800219 } while (!AtomicOps::AcquireLoad(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800220#endif // defined(WEBRTC_WIN)
221}
222
223bool PlatformThread::SetPriority(ThreadPriority priority) {
tommi0f8b4032017-02-22 11:22:05 -0800224#if RTC_DCHECK_IS_ON
225 if (run_function_) {
226 // The non-deprecated way of how this function gets called, is that it must
227 // be called on the worker thread itself.
228 RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
229 } else {
230 // In the case of deprecated use of this method, it must be called on the
231 // same thread as the PlatformThread object is constructed on.
232 RTC_DCHECK(thread_checker_.CalledOnValidThread());
233 RTC_DCHECK(IsRunning());
234 }
235#endif
236
Peter Boströmc6612132015-11-24 18:10:24 +0100237#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100238 return SetThreadPriority(thread_, priority) != FALSE;
Wez0614ed92018-02-06 13:38:21 -0800239#elif defined(__native_client__) || defined(WEBRTC_FUCHSIA)
240 // Setting thread priorities is not supported in NaCl or Fuchsia.
Peter Boströmc6612132015-11-24 18:10:24 +0100241 return true;
242#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
243 // TODO(tommi): Switch to the same mechanism as Chromium uses for changing
244 // thread priorities.
pbos12411ef2015-11-23 14:47:56 -0800245 return true;
246#else
pbos12411ef2015-11-23 14:47:56 -0800247 const int policy = SCHED_FIFO;
pbos12411ef2015-11-23 14:47:56 -0800248 const int min_prio = sched_get_priority_min(policy);
249 const int max_prio = sched_get_priority_max(policy);
250 if (min_prio == -1 || max_prio == -1) {
251 return false;
252 }
253
254 if (max_prio - min_prio <= 2)
255 return false;
256
Peter Boström97c821d2015-11-24 13:48:13 +0100257 // Convert webrtc priority to system priorities:
pbos12411ef2015-11-23 14:47:56 -0800258 sched_param param;
Peter Boström97c821d2015-11-24 13:48:13 +0100259 const int top_prio = max_prio - 1;
260 const int low_prio = min_prio + 1;
261 switch (priority) {
262 case kLowPriority:
263 param.sched_priority = low_prio;
264 break;
265 case kNormalPriority:
266 // The -1 ensures that the kHighPriority is always greater or equal to
267 // kNormalPriority.
268 param.sched_priority = (low_prio + top_prio - 1) / 2;
269 break;
270 case kHighPriority:
271 param.sched_priority = std::max(top_prio - 2, low_prio);
272 break;
273 case kHighestPriority:
274 param.sched_priority = std::max(top_prio - 1, low_prio);
275 break;
276 case kRealtimePriority:
277 param.sched_priority = top_prio;
278 break;
pbos12411ef2015-11-23 14:47:56 -0800279 }
Peter Boström97c821d2015-11-24 13:48:13 +0100280 return pthread_setschedparam(thread_, policy, &param) == 0;
pbos12411ef2015-11-23 14:47:56 -0800281#endif // defined(WEBRTC_WIN)
282}
283
tommi845afa82016-04-22 09:08:44 -0700284#if defined(WEBRTC_WIN)
285bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
286 RTC_DCHECK(thread_checker_.CalledOnValidThread());
287 RTC_DCHECK(IsRunning());
288
289 return QueueUserAPC(function, thread_, data) != FALSE;
290}
291#endif
292
Peter Boström8c38e8b2015-11-26 17:45:47 +0100293} // namespace rtc