blob: d1bd509bf1ad301591b0c4be6e648218cb196de4 [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
95PlatformThread::PlatformThread(ThreadRunFunction func,
96 void* obj,
97 const char* thread_name)
98 : run_function_(func),
99 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);
103}
104
105PlatformThread::~PlatformThread() {
106 RTC_DCHECK(thread_checker_.CalledOnValidThread());
107#if defined(WEBRTC_WIN)
108 RTC_DCHECK(!thread_);
tommi845afa82016-04-22 09:08:44 -0700109 RTC_DCHECK(!thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800110#endif // defined(WEBRTC_WIN)
111}
112
113#if defined(WEBRTC_WIN)
114DWORD WINAPI PlatformThread::StartThread(void* param) {
perkj6a2e20a2016-11-30 04:53:08 -0800115 // The GetLastError() function only returns valid results when it is called
116 // after a Win32 API function that returns a "failed" result. A crash dump
117 // contains the result from GetLastError() and to make sure it does not
118 // falsely report a Windows error we call SetLastError here.
119 ::SetLastError(ERROR_SUCCESS);
pbos12411ef2015-11-23 14:47:56 -0800120 static_cast<PlatformThread*>(param)->Run();
121 return 0;
122}
123#else
124void* PlatformThread::StartThread(void* param) {
125 static_cast<PlatformThread*>(param)->Run();
126 return 0;
127}
128#endif // defined(WEBRTC_WIN)
129
Peter Boström8c38e8b2015-11-26 17:45:47 +0100130void PlatformThread::Start() {
pbos12411ef2015-11-23 14:47:56 -0800131 RTC_DCHECK(thread_checker_.CalledOnValidThread());
132 RTC_DCHECK(!thread_) << "Thread already started?";
133#if defined(WEBRTC_WIN)
134 stop_ = false;
135
136 // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
137 // Set the reserved stack stack size to 1M, which is the default on Windows
138 // and Linux.
pbos12411ef2015-11-23 14:47:56 -0800139 thread_ = ::CreateThread(NULL, 1024 * 1024, &StartThread, this,
tommi845afa82016-04-22 09:08:44 -0700140 STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800141 RTC_CHECK(thread_) << "CreateThread failed";
tommi845afa82016-04-22 09:08:44 -0700142 RTC_DCHECK(thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800143#else
144 ThreadAttributes attr;
145 // Set the stack stack size to 1M.
146 pthread_attr_setstacksize(&attr, 1024 * 1024);
147 RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
148#endif // defined(WEBRTC_WIN)
pbos12411ef2015-11-23 14:47:56 -0800149}
150
Peter Boström8c38e8b2015-11-26 17:45:47 +0100151bool PlatformThread::IsRunning() const {
pbos12411ef2015-11-23 14:47:56 -0800152 RTC_DCHECK(thread_checker_.CalledOnValidThread());
153#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100154 return thread_ != nullptr;
pbos12411ef2015-11-23 14:47:56 -0800155#else
Peter Boström8c38e8b2015-11-26 17:45:47 +0100156 return thread_ != 0;
157#endif // defined(WEBRTC_WIN)
158}
pbos12411ef2015-11-23 14:47:56 -0800159
tommi845afa82016-04-22 09:08:44 -0700160PlatformThreadRef PlatformThread::GetThreadRef() const {
161#if defined(WEBRTC_WIN)
162 return thread_id_;
163#else
164 return thread_;
165#endif // defined(WEBRTC_WIN)
166}
167
Peter Boström8c38e8b2015-11-26 17:45:47 +0100168void PlatformThread::Stop() {
169 RTC_DCHECK(thread_checker_.CalledOnValidThread());
170 if (!IsRunning())
171 return;
172
173#if defined(WEBRTC_WIN)
174 // Set stop_ to |true| on the worker thread.
tommi845afa82016-04-22 09:08:44 -0700175 bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
176 // Queuing the APC can fail if the thread is being terminated.
177 RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
Peter Boström8c38e8b2015-11-26 17:45:47 +0100178 WaitForSingleObject(thread_, INFINITE);
179 CloseHandle(thread_);
180 thread_ = nullptr;
tommi845afa82016-04-22 09:08:44 -0700181 thread_id_ = 0;
Peter Boström8c38e8b2015-11-26 17:45:47 +0100182#else
tommi82ead602017-02-19 16:09:55 -0800183 RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800184 RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
tommi82ead602017-02-19 16:09:55 -0800185 AtomicOps::ReleaseStore(&stop_flag_, 0);
pbos12411ef2015-11-23 14:47:56 -0800186 thread_ = 0;
187#endif // defined(WEBRTC_WIN)
pbos12411ef2015-11-23 14:47:56 -0800188}
189
tommi82ead602017-02-19 16:09:55 -0800190// TODO(tommi): Deprecate the loop behavior in PlatformThread.
191// * Introduce a new callback type that returns void.
192// * Remove potential for a busy loop in PlatformThread.
193// * Delegate the responsibility for how to stop the thread, to the
194// implementation that actually uses the thread.
195// All implementations will need to be aware of how the thread should be stopped
196// and encouraging a busy polling loop, can be costly in terms of power and cpu.
pbos12411ef2015-11-23 14:47:56 -0800197void PlatformThread::Run() {
198 if (!name_.empty())
199 rtc::SetCurrentThreadName(name_.c_str());
tommi82ead602017-02-19 16:09:55 -0800200#if !defined(WEBRTC_MAC) && !defined(WEBRTC_WIN)
201 const struct timespec ts_null = {0};
202#endif
pbos12411ef2015-11-23 14:47:56 -0800203 do {
sprange791ffd2016-01-26 01:53:20 -0800204 // The interface contract of Start/Stop is that for a successful call to
pbos12411ef2015-11-23 14:47:56 -0800205 // Start, there should be at least one call to the run function. So we
206 // call the function before checking |stop_|.
207 if (!run_function_(obj_))
208 break;
209#if defined(WEBRTC_WIN)
210 // Alertable sleep to permit RaiseFlag to run and update |stop_|.
211 SleepEx(0, true);
212 } while (!stop_);
213#else
tommi82ead602017-02-19 16:09:55 -0800214#if defined(WEBRTC_MAC)
215 sched_yield();
216#else
217 nanosleep(&ts_null, nullptr);
218#endif
219 } while (!AtomicOps::AcquireLoad(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800220#endif // defined(WEBRTC_WIN)
221}
222
223bool PlatformThread::SetPriority(ThreadPriority priority) {
224 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Peter Boström8c38e8b2015-11-26 17:45:47 +0100225 RTC_DCHECK(IsRunning());
Peter Boströmc6612132015-11-24 18:10:24 +0100226#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100227 return SetThreadPriority(thread_, priority) != FALSE;
Peter Boströmc6612132015-11-24 18:10:24 +0100228#elif defined(__native_client__)
229 // Setting thread priorities is not supported in NaCl.
230 return true;
231#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
232 // TODO(tommi): Switch to the same mechanism as Chromium uses for changing
233 // thread priorities.
pbos12411ef2015-11-23 14:47:56 -0800234 return true;
235#else
236#ifdef WEBRTC_THREAD_RR
237 const int policy = SCHED_RR;
238#else
239 const int policy = SCHED_FIFO;
240#endif
241 const int min_prio = sched_get_priority_min(policy);
242 const int max_prio = sched_get_priority_max(policy);
243 if (min_prio == -1 || max_prio == -1) {
244 return false;
245 }
246
247 if (max_prio - min_prio <= 2)
248 return false;
249
Peter Boström97c821d2015-11-24 13:48:13 +0100250 // Convert webrtc priority to system priorities:
pbos12411ef2015-11-23 14:47:56 -0800251 sched_param param;
Peter Boström97c821d2015-11-24 13:48:13 +0100252 const int top_prio = max_prio - 1;
253 const int low_prio = min_prio + 1;
254 switch (priority) {
255 case kLowPriority:
256 param.sched_priority = low_prio;
257 break;
258 case kNormalPriority:
259 // The -1 ensures that the kHighPriority is always greater or equal to
260 // kNormalPriority.
261 param.sched_priority = (low_prio + top_prio - 1) / 2;
262 break;
263 case kHighPriority:
264 param.sched_priority = std::max(top_prio - 2, low_prio);
265 break;
266 case kHighestPriority:
267 param.sched_priority = std::max(top_prio - 1, low_prio);
268 break;
269 case kRealtimePriority:
270 param.sched_priority = top_prio;
271 break;
pbos12411ef2015-11-23 14:47:56 -0800272 }
Peter Boström97c821d2015-11-24 13:48:13 +0100273 return pthread_setschedparam(thread_, policy, &param) == 0;
pbos12411ef2015-11-23 14:47:56 -0800274#endif // defined(WEBRTC_WIN)
275}
276
tommi845afa82016-04-22 09:08:44 -0700277#if defined(WEBRTC_WIN)
278bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
279 RTC_DCHECK(thread_checker_.CalledOnValidThread());
280 RTC_DCHECK(IsRunning());
281
282 return QueueUserAPC(function, thread_, data) != FALSE;
283}
284#endif
285
Peter Boström8c38e8b2015-11-26 17:45:47 +0100286} // namespace rtc