blob: 06aee4ed5e579b4cfded914140578e2f3d796615 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020013#include "rtc_base/atomicops.h"
14#include "rtc_base/checks.h"
15#include "rtc_base/timeutils.h"
16#include "rtc_base/trace_event.h"
Tommibebc6902015-05-18 09:51:42 +020017
18#if defined(WEBRTC_LINUX)
Tommiea14f0a2015-05-18 13:51:06 +020019#include <sys/prctl.h>
Tommibebc6902015-05-18 09:51:42 +020020#include <sys/syscall.h>
21#endif
22
Sergey Ulanov6acefdb2017-12-11 17:38:13 -080023#if defined(WEBRTC_FUCHSIA)
24#include <zircon/process.h>
25#endif
26
Tommibebc6902015-05-18 09:51:42 +020027namespace rtc {
28
29PlatformThreadId CurrentThreadId() {
30 PlatformThreadId ret;
31#if defined(WEBRTC_WIN)
32 ret = GetCurrentThreadId();
33#elif defined(WEBRTC_POSIX)
34#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
35 ret = pthread_mach_thread_np(pthread_self());
Tommibebc6902015-05-18 09:51:42 +020036#elif defined(WEBRTC_ANDROID)
37 ret = gettid();
Sergey Ulanov6acefdb2017-12-11 17:38:13 -080038#elif defined(WEBRTC_FUCHSIA)
39 ret = zx_thread_self();
magjedd950d9e2017-08-24 06:41:05 -070040#elif defined(WEBRTC_LINUX)
Sergey Ulanov6acefdb2017-12-11 17:38:13 -080041 ret = syscall(__NR_gettid);
Tommibebc6902015-05-18 09:51:42 +020042#else
43 // Default implementation for nacl and solaris.
44 ret = reinterpret_cast<pid_t>(pthread_self());
45#endif
46#endif // defined(WEBRTC_POSIX)
henrikg91d6ede2015-09-17 00:24:34 -070047 RTC_DCHECK(ret);
Tommibebc6902015-05-18 09:51:42 +020048 return ret;
49}
50
51PlatformThreadRef CurrentThreadRef() {
52#if defined(WEBRTC_WIN)
53 return GetCurrentThreadId();
54#elif defined(WEBRTC_POSIX)
55 return pthread_self();
56#endif
57}
58
59bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
60#if defined(WEBRTC_WIN)
61 return a == b;
62#elif defined(WEBRTC_POSIX)
63 return pthread_equal(a, b);
64#endif
65}
66
Tommiea14f0a2015-05-18 13:51:06 +020067void SetCurrentThreadName(const char* name) {
Tommiea14f0a2015-05-18 13:51:06 +020068#if defined(WEBRTC_WIN)
69 struct {
70 DWORD dwType;
71 LPCSTR szName;
72 DWORD dwThreadID;
73 DWORD dwFlags;
74 } threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};
75
76 __try {
77 ::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
78 reinterpret_cast<ULONG_PTR*>(&threadname_info));
79 } __except (EXCEPTION_EXECUTE_HANDLER) {
80 }
81#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
82 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
83#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
84 pthread_setname_np(name);
85#endif
86}
87
pbos12411ef2015-11-23 14:47:56 -080088namespace {
89#if defined(WEBRTC_WIN)
90void CALLBACK RaiseFlag(ULONG_PTR param) {
91 *reinterpret_cast<bool*>(param) = true;
92}
93#else
94struct ThreadAttributes {
95 ThreadAttributes() { pthread_attr_init(&attr); }
96 ~ThreadAttributes() { pthread_attr_destroy(&attr); }
97 pthread_attr_t* operator&() { return &attr; }
98 pthread_attr_t attr;
99};
pbos12411ef2015-11-23 14:47:56 -0800100#endif // defined(WEBRTC_WIN)
101}
102
tommi0f8b4032017-02-22 11:22:05 -0800103PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
pbos12411ef2015-11-23 14:47:56 -0800104 void* obj,
105 const char* thread_name)
tommi0f8b4032017-02-22 11:22:05 -0800106 : run_function_deprecated_(func),
pbos12411ef2015-11-23 14:47:56 -0800107 obj_(obj),
tommi82ead602017-02-19 16:09:55 -0800108 name_(thread_name ? thread_name : "webrtc") {
pbos12411ef2015-11-23 14:47:56 -0800109 RTC_DCHECK(func);
110 RTC_DCHECK(name_.length() < 64);
tommi0f8b4032017-02-22 11:22:05 -0800111 spawned_thread_checker_.DetachFromThread();
112}
113
114PlatformThread::PlatformThread(ThreadRunFunction func,
115 void* obj,
116 const char* thread_name,
117 ThreadPriority priority /*= kNormalPriority*/)
118 : run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
119 RTC_DCHECK(func);
120 RTC_DCHECK(!name_.empty());
121 // TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
122 RTC_DCHECK(name_.length() < 64);
123 spawned_thread_checker_.DetachFromThread();
pbos12411ef2015-11-23 14:47:56 -0800124}
125
126PlatformThread::~PlatformThread() {
127 RTC_DCHECK(thread_checker_.CalledOnValidThread());
128#if defined(WEBRTC_WIN)
129 RTC_DCHECK(!thread_);
tommi845afa82016-04-22 09:08:44 -0700130 RTC_DCHECK(!thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800131#endif // defined(WEBRTC_WIN)
132}
133
134#if defined(WEBRTC_WIN)
135DWORD WINAPI PlatformThread::StartThread(void* param) {
perkj6a2e20a2016-11-30 04:53:08 -0800136 // The GetLastError() function only returns valid results when it is called
137 // after a Win32 API function that returns a "failed" result. A crash dump
138 // contains the result from GetLastError() and to make sure it does not
139 // falsely report a Windows error we call SetLastError here.
140 ::SetLastError(ERROR_SUCCESS);
pbos12411ef2015-11-23 14:47:56 -0800141 static_cast<PlatformThread*>(param)->Run();
142 return 0;
143}
144#else
145void* PlatformThread::StartThread(void* param) {
146 static_cast<PlatformThread*>(param)->Run();
147 return 0;
148}
149#endif // defined(WEBRTC_WIN)
150
Peter Boström8c38e8b2015-11-26 17:45:47 +0100151void PlatformThread::Start() {
pbos12411ef2015-11-23 14:47:56 -0800152 RTC_DCHECK(thread_checker_.CalledOnValidThread());
153 RTC_DCHECK(!thread_) << "Thread already started?";
154#if defined(WEBRTC_WIN)
155 stop_ = false;
156
157 // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
158 // Set the reserved stack stack size to 1M, which is the default on Windows
159 // and Linux.
deadbeef37f5ecf2017-02-27 14:06:41 -0800160 thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
tommi845afa82016-04-22 09:08:44 -0700161 STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800162 RTC_CHECK(thread_) << "CreateThread failed";
tommi845afa82016-04-22 09:08:44 -0700163 RTC_DCHECK(thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800164#else
165 ThreadAttributes attr;
166 // Set the stack stack size to 1M.
167 pthread_attr_setstacksize(&attr, 1024 * 1024);
168 RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
169#endif // defined(WEBRTC_WIN)
pbos12411ef2015-11-23 14:47:56 -0800170}
171
Peter Boström8c38e8b2015-11-26 17:45:47 +0100172bool PlatformThread::IsRunning() const {
pbos12411ef2015-11-23 14:47:56 -0800173 RTC_DCHECK(thread_checker_.CalledOnValidThread());
174#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100175 return thread_ != nullptr;
pbos12411ef2015-11-23 14:47:56 -0800176#else
Peter Boström8c38e8b2015-11-26 17:45:47 +0100177 return thread_ != 0;
178#endif // defined(WEBRTC_WIN)
179}
pbos12411ef2015-11-23 14:47:56 -0800180
tommi845afa82016-04-22 09:08:44 -0700181PlatformThreadRef PlatformThread::GetThreadRef() const {
182#if defined(WEBRTC_WIN)
183 return thread_id_;
184#else
185 return thread_;
186#endif // defined(WEBRTC_WIN)
187}
188
Peter Boström8c38e8b2015-11-26 17:45:47 +0100189void PlatformThread::Stop() {
190 RTC_DCHECK(thread_checker_.CalledOnValidThread());
191 if (!IsRunning())
192 return;
193
194#if defined(WEBRTC_WIN)
195 // Set stop_ to |true| on the worker thread.
tommi845afa82016-04-22 09:08:44 -0700196 bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
197 // Queuing the APC can fail if the thread is being terminated.
198 RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
Peter Boström8c38e8b2015-11-26 17:45:47 +0100199 WaitForSingleObject(thread_, INFINITE);
200 CloseHandle(thread_);
201 thread_ = nullptr;
tommi845afa82016-04-22 09:08:44 -0700202 thread_id_ = 0;
Peter Boström8c38e8b2015-11-26 17:45:47 +0100203#else
tommi0f8b4032017-02-22 11:22:05 -0800204 if (!run_function_)
205 RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800206 RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
tommi0f8b4032017-02-22 11:22:05 -0800207 if (!run_function_)
208 AtomicOps::ReleaseStore(&stop_flag_, 0);
pbos12411ef2015-11-23 14:47:56 -0800209 thread_ = 0;
210#endif // defined(WEBRTC_WIN)
tommi0f8b4032017-02-22 11:22:05 -0800211 spawned_thread_checker_.DetachFromThread();
pbos12411ef2015-11-23 14:47:56 -0800212}
213
tommi82ead602017-02-19 16:09:55 -0800214// TODO(tommi): Deprecate the loop behavior in PlatformThread.
215// * Introduce a new callback type that returns void.
216// * Remove potential for a busy loop in PlatformThread.
217// * Delegate the responsibility for how to stop the thread, to the
218// implementation that actually uses the thread.
219// All implementations will need to be aware of how the thread should be stopped
220// and encouraging a busy polling loop, can be costly in terms of power and cpu.
pbos12411ef2015-11-23 14:47:56 -0800221void PlatformThread::Run() {
tommi0f8b4032017-02-22 11:22:05 -0800222 // Attach the worker thread checker to this thread.
223 RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
224 rtc::SetCurrentThreadName(name_.c_str());
225
226 if (run_function_) {
227 SetPriority(priority_);
228 run_function_(obj_);
229 return;
230 }
tommi500f1b72017-03-02 07:07:09 -0800231
232// TODO(tommi): Delete the rest of this function when looping isn't supported.
233#if RTC_DCHECK_IS_ON
234 // These constants control the busy loop detection algorithm below.
235 // |kMaxLoopCount| controls the limit for how many times we allow the loop
236 // to run within a period, before DCHECKing.
237 // |kPeriodToMeasureMs| controls how long that period is.
238 static const int kMaxLoopCount = 1000;
239 static const int kPeriodToMeasureMs = 100;
240 int64_t loop_stamps[kMaxLoopCount] = {};
241 int64_t sequence_nr = 0;
danilchap27523472017-02-28 06:20:38 -0800242#endif
tommi500f1b72017-03-02 07:07:09 -0800243
pbos12411ef2015-11-23 14:47:56 -0800244 do {
tommidb23ea62017-03-03 07:21:18 -0800245 TRACE_EVENT1("webrtc", "PlatformThread::Run", "name", name_.c_str());
246
sprange791ffd2016-01-26 01:53:20 -0800247 // The interface contract of Start/Stop is that for a successful call to
pbos12411ef2015-11-23 14:47:56 -0800248 // Start, there should be at least one call to the run function. So we
249 // call the function before checking |stop_|.
tommi0f8b4032017-02-22 11:22:05 -0800250 if (!run_function_deprecated_(obj_))
pbos12411ef2015-11-23 14:47:56 -0800251 break;
tommi500f1b72017-03-02 07:07:09 -0800252#if RTC_DCHECK_IS_ON
253 auto id = sequence_nr % kMaxLoopCount;
254 loop_stamps[id] = rtc::TimeMillis();
255 if (sequence_nr > kMaxLoopCount) {
256 auto compare_id = (id + 1) % kMaxLoopCount;
257 auto diff = loop_stamps[id] - loop_stamps[compare_id];
258 RTC_DCHECK_GE(diff, 0);
259 if (diff < kPeriodToMeasureMs) {
260 RTC_NOTREACHED() << "This thread is too busy: " << name_ << " " << diff
261 << "ms sequence=" << sequence_nr << " "
262 << loop_stamps[id] << " vs " << loop_stamps[compare_id]
263 << ", " << id << " vs " << compare_id;
264 }
265 }
266 ++sequence_nr;
267#endif
pbos12411ef2015-11-23 14:47:56 -0800268#if defined(WEBRTC_WIN)
269 // Alertable sleep to permit RaiseFlag to run and update |stop_|.
270 SleepEx(0, true);
271 } while (!stop_);
272#else
tommi0473b1d2017-03-02 08:08:59 -0800273#if defined(WEBRTC_MAC)
274 sched_yield();
275#else
tommi500f1b72017-03-02 07:07:09 -0800276 static const struct timespec ts_null = {0};
danilchap27523472017-02-28 06:20:38 -0800277 nanosleep(&ts_null, nullptr);
278#endif
tommi82ead602017-02-19 16:09:55 -0800279 } while (!AtomicOps::AcquireLoad(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800280#endif // defined(WEBRTC_WIN)
281}
282
283bool PlatformThread::SetPriority(ThreadPriority priority) {
tommi0f8b4032017-02-22 11:22:05 -0800284#if RTC_DCHECK_IS_ON
285 if (run_function_) {
286 // The non-deprecated way of how this function gets called, is that it must
287 // be called on the worker thread itself.
tommi7c3da272017-03-20 03:47:17 -0700288 RTC_DCHECK(!thread_checker_.CalledOnValidThread());
tommi0f8b4032017-02-22 11:22:05 -0800289 RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
290 } else {
291 // In the case of deprecated use of this method, it must be called on the
292 // same thread as the PlatformThread object is constructed on.
293 RTC_DCHECK(thread_checker_.CalledOnValidThread());
294 RTC_DCHECK(IsRunning());
295 }
296#endif
297
Peter Boströmc6612132015-11-24 18:10:24 +0100298#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100299 return SetThreadPriority(thread_, priority) != FALSE;
Peter Boströmc6612132015-11-24 18:10:24 +0100300#elif defined(__native_client__)
301 // Setting thread priorities is not supported in NaCl.
302 return true;
303#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
304 // TODO(tommi): Switch to the same mechanism as Chromium uses for changing
305 // thread priorities.
pbos12411ef2015-11-23 14:47:56 -0800306 return true;
307#else
308#ifdef WEBRTC_THREAD_RR
309 const int policy = SCHED_RR;
310#else
311 const int policy = SCHED_FIFO;
312#endif
313 const int min_prio = sched_get_priority_min(policy);
314 const int max_prio = sched_get_priority_max(policy);
315 if (min_prio == -1 || max_prio == -1) {
316 return false;
317 }
318
319 if (max_prio - min_prio <= 2)
320 return false;
321
Peter Boström97c821d2015-11-24 13:48:13 +0100322 // Convert webrtc priority to system priorities:
pbos12411ef2015-11-23 14:47:56 -0800323 sched_param param;
Peter Boström97c821d2015-11-24 13:48:13 +0100324 const int top_prio = max_prio - 1;
325 const int low_prio = min_prio + 1;
326 switch (priority) {
327 case kLowPriority:
328 param.sched_priority = low_prio;
329 break;
330 case kNormalPriority:
331 // The -1 ensures that the kHighPriority is always greater or equal to
332 // kNormalPriority.
333 param.sched_priority = (low_prio + top_prio - 1) / 2;
334 break;
335 case kHighPriority:
336 param.sched_priority = std::max(top_prio - 2, low_prio);
337 break;
338 case kHighestPriority:
339 param.sched_priority = std::max(top_prio - 1, low_prio);
340 break;
341 case kRealtimePriority:
342 param.sched_priority = top_prio;
343 break;
pbos12411ef2015-11-23 14:47:56 -0800344 }
Peter Boström97c821d2015-11-24 13:48:13 +0100345 return pthread_setschedparam(thread_, policy, &param) == 0;
pbos12411ef2015-11-23 14:47:56 -0800346#endif // defined(WEBRTC_WIN)
347}
348
tommi845afa82016-04-22 09:08:44 -0700349#if defined(WEBRTC_WIN)
350bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
351 RTC_DCHECK(thread_checker_.CalledOnValidThread());
352 RTC_DCHECK(IsRunning());
353
354 return QueueUserAPC(function, thread_, data) != FALSE;
355}
356#endif
357
Peter Boström8c38e8b2015-11-26 17:45:47 +0100358} // namespace rtc