blob: 52f88106b7cab16f34fc4c3e2b233ba047a1a642 [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
11#include "webrtc/base/platform_thread.h"
12
tommi82ead602017-02-19 16:09:55 -080013#include "webrtc/base/atomicops.h"
Tommibebc6902015-05-18 09:51:42 +020014#include "webrtc/base/checks.h"
15
16#if defined(WEBRTC_LINUX)
Tommiea14f0a2015-05-18 13:51:06 +020017#include <sys/prctl.h>
Tommibebc6902015-05-18 09:51:42 +020018#include <sys/syscall.h>
19#endif
20
21namespace rtc {
22
23PlatformThreadId CurrentThreadId() {
24 PlatformThreadId ret;
25#if defined(WEBRTC_WIN)
26 ret = GetCurrentThreadId();
27#elif defined(WEBRTC_POSIX)
28#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
29 ret = pthread_mach_thread_np(pthread_self());
30#elif defined(WEBRTC_LINUX)
31 ret = syscall(__NR_gettid);
32#elif defined(WEBRTC_ANDROID)
33 ret = gettid();
34#else
35 // Default implementation for nacl and solaris.
36 ret = reinterpret_cast<pid_t>(pthread_self());
37#endif
38#endif // defined(WEBRTC_POSIX)
henrikg91d6ede2015-09-17 00:24:34 -070039 RTC_DCHECK(ret);
Tommibebc6902015-05-18 09:51:42 +020040 return ret;
41}
42
43PlatformThreadRef CurrentThreadRef() {
44#if defined(WEBRTC_WIN)
45 return GetCurrentThreadId();
46#elif defined(WEBRTC_POSIX)
47 return pthread_self();
48#endif
49}
50
51bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
52#if defined(WEBRTC_WIN)
53 return a == b;
54#elif defined(WEBRTC_POSIX)
55 return pthread_equal(a, b);
56#endif
57}
58
Tommiea14f0a2015-05-18 13:51:06 +020059void SetCurrentThreadName(const char* name) {
Tommiea14f0a2015-05-18 13:51:06 +020060#if defined(WEBRTC_WIN)
61 struct {
62 DWORD dwType;
63 LPCSTR szName;
64 DWORD dwThreadID;
65 DWORD dwFlags;
66 } threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};
67
68 __try {
69 ::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
70 reinterpret_cast<ULONG_PTR*>(&threadname_info));
71 } __except (EXCEPTION_EXECUTE_HANDLER) {
72 }
73#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
74 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
75#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
76 pthread_setname_np(name);
77#endif
78}
79
pbos12411ef2015-11-23 14:47:56 -080080namespace {
81#if defined(WEBRTC_WIN)
82void CALLBACK RaiseFlag(ULONG_PTR param) {
83 *reinterpret_cast<bool*>(param) = true;
84}
85#else
86struct ThreadAttributes {
87 ThreadAttributes() { pthread_attr_init(&attr); }
88 ~ThreadAttributes() { pthread_attr_destroy(&attr); }
89 pthread_attr_t* operator&() { return &attr; }
90 pthread_attr_t attr;
91};
pbos12411ef2015-11-23 14:47:56 -080092#endif // defined(WEBRTC_WIN)
93}
94
tommi0f8b4032017-02-22 11:22:05 -080095PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
pbos12411ef2015-11-23 14:47:56 -080096 void* obj,
97 const char* thread_name)
tommi0f8b4032017-02-22 11:22:05 -080098 : run_function_deprecated_(func),
pbos12411ef2015-11-23 14:47:56 -080099 obj_(obj),
tommi82ead602017-02-19 16:09:55 -0800100 name_(thread_name ? thread_name : "webrtc") {
pbos12411ef2015-11-23 14:47:56 -0800101 RTC_DCHECK(func);
102 RTC_DCHECK(name_.length() < 64);
tommi0f8b4032017-02-22 11:22:05 -0800103 spawned_thread_checker_.DetachFromThread();
104}
105
106PlatformThread::PlatformThread(ThreadRunFunction func,
107 void* obj,
108 const char* thread_name,
109 ThreadPriority priority /*= kNormalPriority*/)
110 : run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
111 RTC_DCHECK(func);
112 RTC_DCHECK(!name_.empty());
113 // TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
114 RTC_DCHECK(name_.length() < 64);
115 spawned_thread_checker_.DetachFromThread();
pbos12411ef2015-11-23 14:47:56 -0800116}
117
118PlatformThread::~PlatformThread() {
119 RTC_DCHECK(thread_checker_.CalledOnValidThread());
120#if defined(WEBRTC_WIN)
121 RTC_DCHECK(!thread_);
tommi845afa82016-04-22 09:08:44 -0700122 RTC_DCHECK(!thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800123#endif // defined(WEBRTC_WIN)
124}
125
126#if defined(WEBRTC_WIN)
127DWORD WINAPI PlatformThread::StartThread(void* param) {
perkj6a2e20a2016-11-30 04:53:08 -0800128 // The GetLastError() function only returns valid results when it is called
129 // after a Win32 API function that returns a "failed" result. A crash dump
130 // contains the result from GetLastError() and to make sure it does not
131 // falsely report a Windows error we call SetLastError here.
132 ::SetLastError(ERROR_SUCCESS);
pbos12411ef2015-11-23 14:47:56 -0800133 static_cast<PlatformThread*>(param)->Run();
134 return 0;
135}
136#else
137void* PlatformThread::StartThread(void* param) {
138 static_cast<PlatformThread*>(param)->Run();
139 return 0;
140}
141#endif // defined(WEBRTC_WIN)
142
Peter Boström8c38e8b2015-11-26 17:45:47 +0100143void PlatformThread::Start() {
pbos12411ef2015-11-23 14:47:56 -0800144 RTC_DCHECK(thread_checker_.CalledOnValidThread());
145 RTC_DCHECK(!thread_) << "Thread already started?";
146#if defined(WEBRTC_WIN)
147 stop_ = false;
148
149 // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
150 // Set the reserved stack stack size to 1M, which is the default on Windows
151 // and Linux.
deadbeef37f5ecf2017-02-27 14:06:41 -0800152 thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
tommi845afa82016-04-22 09:08:44 -0700153 STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800154 RTC_CHECK(thread_) << "CreateThread failed";
tommi845afa82016-04-22 09:08:44 -0700155 RTC_DCHECK(thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800156#else
157 ThreadAttributes attr;
158 // Set the stack stack size to 1M.
159 pthread_attr_setstacksize(&attr, 1024 * 1024);
160 RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
161#endif // defined(WEBRTC_WIN)
pbos12411ef2015-11-23 14:47:56 -0800162}
163
Peter Boström8c38e8b2015-11-26 17:45:47 +0100164bool PlatformThread::IsRunning() const {
pbos12411ef2015-11-23 14:47:56 -0800165 RTC_DCHECK(thread_checker_.CalledOnValidThread());
166#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100167 return thread_ != nullptr;
pbos12411ef2015-11-23 14:47:56 -0800168#else
Peter Boström8c38e8b2015-11-26 17:45:47 +0100169 return thread_ != 0;
170#endif // defined(WEBRTC_WIN)
171}
pbos12411ef2015-11-23 14:47:56 -0800172
tommi845afa82016-04-22 09:08:44 -0700173PlatformThreadRef PlatformThread::GetThreadRef() const {
174#if defined(WEBRTC_WIN)
175 return thread_id_;
176#else
177 return thread_;
178#endif // defined(WEBRTC_WIN)
179}
180
Peter Boström8c38e8b2015-11-26 17:45:47 +0100181void PlatformThread::Stop() {
182 RTC_DCHECK(thread_checker_.CalledOnValidThread());
183 if (!IsRunning())
184 return;
185
186#if defined(WEBRTC_WIN)
187 // Set stop_ to |true| on the worker thread.
tommi845afa82016-04-22 09:08:44 -0700188 bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
189 // Queuing the APC can fail if the thread is being terminated.
190 RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
Peter Boström8c38e8b2015-11-26 17:45:47 +0100191 WaitForSingleObject(thread_, INFINITE);
192 CloseHandle(thread_);
193 thread_ = nullptr;
tommi845afa82016-04-22 09:08:44 -0700194 thread_id_ = 0;
Peter Boström8c38e8b2015-11-26 17:45:47 +0100195#else
tommi0f8b4032017-02-22 11:22:05 -0800196 if (!run_function_)
197 RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800198 RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
tommi0f8b4032017-02-22 11:22:05 -0800199 if (!run_function_)
200 AtomicOps::ReleaseStore(&stop_flag_, 0);
pbos12411ef2015-11-23 14:47:56 -0800201 thread_ = 0;
202#endif // defined(WEBRTC_WIN)
tommi0f8b4032017-02-22 11:22:05 -0800203 spawned_thread_checker_.DetachFromThread();
pbos12411ef2015-11-23 14:47:56 -0800204}
205
tommi82ead602017-02-19 16:09:55 -0800206// TODO(tommi): Deprecate the loop behavior in PlatformThread.
207// * Introduce a new callback type that returns void.
208// * Remove potential for a busy loop in PlatformThread.
209// * Delegate the responsibility for how to stop the thread, to the
210// implementation that actually uses the thread.
211// All implementations will need to be aware of how the thread should be stopped
212// and encouraging a busy polling loop, can be costly in terms of power and cpu.
pbos12411ef2015-11-23 14:47:56 -0800213void PlatformThread::Run() {
tommi0f8b4032017-02-22 11:22:05 -0800214 // Attach the worker thread checker to this thread.
215 RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
216 rtc::SetCurrentThreadName(name_.c_str());
217
218 if (run_function_) {
219 SetPriority(priority_);
220 run_function_(obj_);
221 return;
222 }
223// TODO(tommi): Delete the below.
tommi3ba1a8c2017-02-24 09:12:32 -0800224#if !defined(WEBRTC_MAC) && !defined(WEBRTC_WIN)
225 const struct timespec ts_null = {0};
226#endif
pbos12411ef2015-11-23 14:47:56 -0800227 do {
sprange791ffd2016-01-26 01:53:20 -0800228 // The interface contract of Start/Stop is that for a successful call to
pbos12411ef2015-11-23 14:47:56 -0800229 // Start, there should be at least one call to the run function. So we
230 // call the function before checking |stop_|.
tommi0f8b4032017-02-22 11:22:05 -0800231 if (!run_function_deprecated_(obj_))
pbos12411ef2015-11-23 14:47:56 -0800232 break;
233#if defined(WEBRTC_WIN)
234 // Alertable sleep to permit RaiseFlag to run and update |stop_|.
235 SleepEx(0, true);
236 } while (!stop_);
237#else
tommi3ba1a8c2017-02-24 09:12:32 -0800238#if defined(WEBRTC_MAC)
tommi82ead602017-02-19 16:09:55 -0800239 sched_yield();
tommi3ba1a8c2017-02-24 09:12:32 -0800240#else
241 nanosleep(&ts_null, nullptr);
242#endif
tommi82ead602017-02-19 16:09:55 -0800243 } while (!AtomicOps::AcquireLoad(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800244#endif // defined(WEBRTC_WIN)
245}
246
247bool PlatformThread::SetPriority(ThreadPriority priority) {
tommi0f8b4032017-02-22 11:22:05 -0800248#if RTC_DCHECK_IS_ON
249 if (run_function_) {
250 // The non-deprecated way of how this function gets called, is that it must
251 // be called on the worker thread itself.
252 RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
253 } else {
254 // In the case of deprecated use of this method, it must be called on the
255 // same thread as the PlatformThread object is constructed on.
256 RTC_DCHECK(thread_checker_.CalledOnValidThread());
257 RTC_DCHECK(IsRunning());
258 }
259#endif
260
Peter Boströmc6612132015-11-24 18:10:24 +0100261#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100262 return SetThreadPriority(thread_, priority) != FALSE;
Peter Boströmc6612132015-11-24 18:10:24 +0100263#elif defined(__native_client__)
264 // Setting thread priorities is not supported in NaCl.
265 return true;
266#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
267 // TODO(tommi): Switch to the same mechanism as Chromium uses for changing
268 // thread priorities.
pbos12411ef2015-11-23 14:47:56 -0800269 return true;
270#else
271#ifdef WEBRTC_THREAD_RR
272 const int policy = SCHED_RR;
273#else
274 const int policy = SCHED_FIFO;
275#endif
276 const int min_prio = sched_get_priority_min(policy);
277 const int max_prio = sched_get_priority_max(policy);
278 if (min_prio == -1 || max_prio == -1) {
279 return false;
280 }
281
282 if (max_prio - min_prio <= 2)
283 return false;
284
Peter Boström97c821d2015-11-24 13:48:13 +0100285 // Convert webrtc priority to system priorities:
pbos12411ef2015-11-23 14:47:56 -0800286 sched_param param;
Peter Boström97c821d2015-11-24 13:48:13 +0100287 const int top_prio = max_prio - 1;
288 const int low_prio = min_prio + 1;
289 switch (priority) {
290 case kLowPriority:
291 param.sched_priority = low_prio;
292 break;
293 case kNormalPriority:
294 // The -1 ensures that the kHighPriority is always greater or equal to
295 // kNormalPriority.
296 param.sched_priority = (low_prio + top_prio - 1) / 2;
297 break;
298 case kHighPriority:
299 param.sched_priority = std::max(top_prio - 2, low_prio);
300 break;
301 case kHighestPriority:
302 param.sched_priority = std::max(top_prio - 1, low_prio);
303 break;
304 case kRealtimePriority:
305 param.sched_priority = top_prio;
306 break;
pbos12411ef2015-11-23 14:47:56 -0800307 }
Peter Boström97c821d2015-11-24 13:48:13 +0100308 return pthread_setschedparam(thread_, policy, &param) == 0;
pbos12411ef2015-11-23 14:47:56 -0800309#endif // defined(WEBRTC_WIN)
310}
311
tommi845afa82016-04-22 09:08:44 -0700312#if defined(WEBRTC_WIN)
313bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
314 RTC_DCHECK(thread_checker_.CalledOnValidThread());
315 RTC_DCHECK(IsRunning());
316
317 return QueueUserAPC(function, thread_, data) != FALSE;
318}
319#endif
320
Peter Boström8c38e8b2015-11-26 17:45:47 +0100321} // namespace rtc