blob: afacfdca2d22c8945fb4274fdfa506f2a7cfad0e [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"
tommi500f1b72017-03-02 07:07:09 -080015#include "webrtc/base/timeutils.h"
Tommibebc6902015-05-18 09:51:42 +020016
17#if defined(WEBRTC_LINUX)
Tommiea14f0a2015-05-18 13:51:06 +020018#include <sys/prctl.h>
Tommibebc6902015-05-18 09:51:42 +020019#include <sys/syscall.h>
20#endif
21
22namespace rtc {
23
24PlatformThreadId CurrentThreadId() {
25 PlatformThreadId ret;
26#if defined(WEBRTC_WIN)
27 ret = GetCurrentThreadId();
28#elif defined(WEBRTC_POSIX)
29#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
30 ret = pthread_mach_thread_np(pthread_self());
31#elif defined(WEBRTC_LINUX)
32 ret = syscall(__NR_gettid);
33#elif defined(WEBRTC_ANDROID)
34 ret = gettid();
35#else
36 // Default implementation for nacl and solaris.
37 ret = reinterpret_cast<pid_t>(pthread_self());
38#endif
39#endif // defined(WEBRTC_POSIX)
henrikg91d6ede2015-09-17 00:24:34 -070040 RTC_DCHECK(ret);
Tommibebc6902015-05-18 09:51:42 +020041 return ret;
42}
43
44PlatformThreadRef CurrentThreadRef() {
45#if defined(WEBRTC_WIN)
46 return GetCurrentThreadId();
47#elif defined(WEBRTC_POSIX)
48 return pthread_self();
49#endif
50}
51
52bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
53#if defined(WEBRTC_WIN)
54 return a == b;
55#elif defined(WEBRTC_POSIX)
56 return pthread_equal(a, b);
57#endif
58}
59
Tommiea14f0a2015-05-18 13:51:06 +020060void SetCurrentThreadName(const char* name) {
Tommiea14f0a2015-05-18 13:51:06 +020061#if defined(WEBRTC_WIN)
62 struct {
63 DWORD dwType;
64 LPCSTR szName;
65 DWORD dwThreadID;
66 DWORD dwFlags;
67 } threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};
68
69 __try {
70 ::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
71 reinterpret_cast<ULONG_PTR*>(&threadname_info));
72 } __except (EXCEPTION_EXECUTE_HANDLER) {
73 }
74#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
75 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
76#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
77 pthread_setname_np(name);
78#endif
79}
80
pbos12411ef2015-11-23 14:47:56 -080081namespace {
82#if defined(WEBRTC_WIN)
83void CALLBACK RaiseFlag(ULONG_PTR param) {
84 *reinterpret_cast<bool*>(param) = true;
85}
86#else
87struct ThreadAttributes {
88 ThreadAttributes() { pthread_attr_init(&attr); }
89 ~ThreadAttributes() { pthread_attr_destroy(&attr); }
90 pthread_attr_t* operator&() { return &attr; }
91 pthread_attr_t attr;
92};
pbos12411ef2015-11-23 14:47:56 -080093#endif // defined(WEBRTC_WIN)
94}
95
tommi0f8b4032017-02-22 11:22:05 -080096PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
pbos12411ef2015-11-23 14:47:56 -080097 void* obj,
98 const char* thread_name)
tommi0f8b4032017-02-22 11:22:05 -080099 : run_function_deprecated_(func),
pbos12411ef2015-11-23 14:47:56 -0800100 obj_(obj),
tommi82ead602017-02-19 16:09:55 -0800101 name_(thread_name ? thread_name : "webrtc") {
pbos12411ef2015-11-23 14:47:56 -0800102 RTC_DCHECK(func);
103 RTC_DCHECK(name_.length() < 64);
tommi0f8b4032017-02-22 11:22:05 -0800104 spawned_thread_checker_.DetachFromThread();
105}
106
107PlatformThread::PlatformThread(ThreadRunFunction func,
108 void* obj,
109 const char* thread_name,
110 ThreadPriority priority /*= kNormalPriority*/)
111 : run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
112 RTC_DCHECK(func);
113 RTC_DCHECK(!name_.empty());
114 // TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
115 RTC_DCHECK(name_.length() < 64);
116 spawned_thread_checker_.DetachFromThread();
pbos12411ef2015-11-23 14:47:56 -0800117}
118
119PlatformThread::~PlatformThread() {
120 RTC_DCHECK(thread_checker_.CalledOnValidThread());
121#if defined(WEBRTC_WIN)
122 RTC_DCHECK(!thread_);
tommi845afa82016-04-22 09:08:44 -0700123 RTC_DCHECK(!thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800124#endif // defined(WEBRTC_WIN)
125}
126
127#if defined(WEBRTC_WIN)
128DWORD WINAPI PlatformThread::StartThread(void* param) {
perkj6a2e20a2016-11-30 04:53:08 -0800129 // The GetLastError() function only returns valid results when it is called
130 // after a Win32 API function that returns a "failed" result. A crash dump
131 // contains the result from GetLastError() and to make sure it does not
132 // falsely report a Windows error we call SetLastError here.
133 ::SetLastError(ERROR_SUCCESS);
pbos12411ef2015-11-23 14:47:56 -0800134 static_cast<PlatformThread*>(param)->Run();
135 return 0;
136}
137#else
138void* PlatformThread::StartThread(void* param) {
139 static_cast<PlatformThread*>(param)->Run();
140 return 0;
141}
142#endif // defined(WEBRTC_WIN)
143
Peter Boström8c38e8b2015-11-26 17:45:47 +0100144void PlatformThread::Start() {
pbos12411ef2015-11-23 14:47:56 -0800145 RTC_DCHECK(thread_checker_.CalledOnValidThread());
146 RTC_DCHECK(!thread_) << "Thread already started?";
147#if defined(WEBRTC_WIN)
148 stop_ = false;
149
150 // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
151 // Set the reserved stack stack size to 1M, which is the default on Windows
152 // and Linux.
deadbeef37f5ecf2017-02-27 14:06:41 -0800153 thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
tommi845afa82016-04-22 09:08:44 -0700154 STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800155 RTC_CHECK(thread_) << "CreateThread failed";
tommi845afa82016-04-22 09:08:44 -0700156 RTC_DCHECK(thread_id_);
pbos12411ef2015-11-23 14:47:56 -0800157#else
158 ThreadAttributes attr;
159 // Set the stack stack size to 1M.
160 pthread_attr_setstacksize(&attr, 1024 * 1024);
161 RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
162#endif // defined(WEBRTC_WIN)
pbos12411ef2015-11-23 14:47:56 -0800163}
164
Peter Boström8c38e8b2015-11-26 17:45:47 +0100165bool PlatformThread::IsRunning() const {
pbos12411ef2015-11-23 14:47:56 -0800166 RTC_DCHECK(thread_checker_.CalledOnValidThread());
167#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100168 return thread_ != nullptr;
pbos12411ef2015-11-23 14:47:56 -0800169#else
Peter Boström8c38e8b2015-11-26 17:45:47 +0100170 return thread_ != 0;
171#endif // defined(WEBRTC_WIN)
172}
pbos12411ef2015-11-23 14:47:56 -0800173
tommi845afa82016-04-22 09:08:44 -0700174PlatformThreadRef PlatformThread::GetThreadRef() const {
175#if defined(WEBRTC_WIN)
176 return thread_id_;
177#else
178 return thread_;
179#endif // defined(WEBRTC_WIN)
180}
181
Peter Boström8c38e8b2015-11-26 17:45:47 +0100182void PlatformThread::Stop() {
183 RTC_DCHECK(thread_checker_.CalledOnValidThread());
184 if (!IsRunning())
185 return;
186
187#if defined(WEBRTC_WIN)
188 // Set stop_ to |true| on the worker thread.
tommi845afa82016-04-22 09:08:44 -0700189 bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
190 // Queuing the APC can fail if the thread is being terminated.
191 RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
Peter Boström8c38e8b2015-11-26 17:45:47 +0100192 WaitForSingleObject(thread_, INFINITE);
193 CloseHandle(thread_);
194 thread_ = nullptr;
tommi845afa82016-04-22 09:08:44 -0700195 thread_id_ = 0;
Peter Boström8c38e8b2015-11-26 17:45:47 +0100196#else
tommi0f8b4032017-02-22 11:22:05 -0800197 if (!run_function_)
198 RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800199 RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
tommi0f8b4032017-02-22 11:22:05 -0800200 if (!run_function_)
201 AtomicOps::ReleaseStore(&stop_flag_, 0);
pbos12411ef2015-11-23 14:47:56 -0800202 thread_ = 0;
203#endif // defined(WEBRTC_WIN)
tommi0f8b4032017-02-22 11:22:05 -0800204 spawned_thread_checker_.DetachFromThread();
pbos12411ef2015-11-23 14:47:56 -0800205}
206
tommi82ead602017-02-19 16:09:55 -0800207// TODO(tommi): Deprecate the loop behavior in PlatformThread.
208// * Introduce a new callback type that returns void.
209// * Remove potential for a busy loop in PlatformThread.
210// * Delegate the responsibility for how to stop the thread, to the
211// implementation that actually uses the thread.
212// All implementations will need to be aware of how the thread should be stopped
213// and encouraging a busy polling loop, can be costly in terms of power and cpu.
pbos12411ef2015-11-23 14:47:56 -0800214void PlatformThread::Run() {
tommi0f8b4032017-02-22 11:22:05 -0800215 // Attach the worker thread checker to this thread.
216 RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
217 rtc::SetCurrentThreadName(name_.c_str());
218
219 if (run_function_) {
220 SetPriority(priority_);
221 run_function_(obj_);
222 return;
223 }
tommi500f1b72017-03-02 07:07:09 -0800224
225// TODO(tommi): Delete the rest of this function when looping isn't supported.
226#if RTC_DCHECK_IS_ON
227 // These constants control the busy loop detection algorithm below.
228 // |kMaxLoopCount| controls the limit for how many times we allow the loop
229 // to run within a period, before DCHECKing.
230 // |kPeriodToMeasureMs| controls how long that period is.
231 static const int kMaxLoopCount = 1000;
232 static const int kPeriodToMeasureMs = 100;
233 int64_t loop_stamps[kMaxLoopCount] = {};
234 int64_t sequence_nr = 0;
danilchap27523472017-02-28 06:20:38 -0800235#endif
tommi500f1b72017-03-02 07:07:09 -0800236
pbos12411ef2015-11-23 14:47:56 -0800237 do {
sprange791ffd2016-01-26 01:53:20 -0800238 // The interface contract of Start/Stop is that for a successful call to
pbos12411ef2015-11-23 14:47:56 -0800239 // Start, there should be at least one call to the run function. So we
240 // call the function before checking |stop_|.
tommi0f8b4032017-02-22 11:22:05 -0800241 if (!run_function_deprecated_(obj_))
pbos12411ef2015-11-23 14:47:56 -0800242 break;
tommi500f1b72017-03-02 07:07:09 -0800243#if RTC_DCHECK_IS_ON
244 auto id = sequence_nr % kMaxLoopCount;
245 loop_stamps[id] = rtc::TimeMillis();
246 if (sequence_nr > kMaxLoopCount) {
247 auto compare_id = (id + 1) % kMaxLoopCount;
248 auto diff = loop_stamps[id] - loop_stamps[compare_id];
249 RTC_DCHECK_GE(diff, 0);
250 if (diff < kPeriodToMeasureMs) {
251 RTC_NOTREACHED() << "This thread is too busy: " << name_ << " " << diff
252 << "ms sequence=" << sequence_nr << " "
253 << loop_stamps[id] << " vs " << loop_stamps[compare_id]
254 << ", " << id << " vs " << compare_id;
255 }
256 }
257 ++sequence_nr;
258#endif
pbos12411ef2015-11-23 14:47:56 -0800259#if defined(WEBRTC_WIN)
260 // Alertable sleep to permit RaiseFlag to run and update |stop_|.
261 SleepEx(0, true);
262 } while (!stop_);
263#else
tommi500f1b72017-03-02 07:07:09 -0800264#if defined(UNDEFINED_SANITIZER) || defined(WEBRTC_ANDROID)
265 // UBSAN and Android don't like |sched_yield()| that much.
266 static const struct timespec ts_null = {0};
danilchap27523472017-02-28 06:20:38 -0800267 nanosleep(&ts_null, nullptr);
tommi500f1b72017-03-02 07:07:09 -0800268#else // !(defined(UNDEFINED_SANITIZER) || defined(WEBRTC_ANDROID))
269 // Mac and Linux show better performance with sched_yield.
270 sched_yield();
danilchap27523472017-02-28 06:20:38 -0800271#endif
tommi82ead602017-02-19 16:09:55 -0800272 } while (!AtomicOps::AcquireLoad(&stop_flag_));
pbos12411ef2015-11-23 14:47:56 -0800273#endif // defined(WEBRTC_WIN)
274}
275
276bool PlatformThread::SetPriority(ThreadPriority priority) {
tommi0f8b4032017-02-22 11:22:05 -0800277#if RTC_DCHECK_IS_ON
278 if (run_function_) {
279 // The non-deprecated way of how this function gets called, is that it must
280 // be called on the worker thread itself.
281 RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
282 } else {
283 // In the case of deprecated use of this method, it must be called on the
284 // same thread as the PlatformThread object is constructed on.
285 RTC_DCHECK(thread_checker_.CalledOnValidThread());
286 RTC_DCHECK(IsRunning());
287 }
288#endif
289
Peter Boströmc6612132015-11-24 18:10:24 +0100290#if defined(WEBRTC_WIN)
Peter Boström8c38e8b2015-11-26 17:45:47 +0100291 return SetThreadPriority(thread_, priority) != FALSE;
Peter Boströmc6612132015-11-24 18:10:24 +0100292#elif defined(__native_client__)
293 // Setting thread priorities is not supported in NaCl.
294 return true;
295#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
296 // TODO(tommi): Switch to the same mechanism as Chromium uses for changing
297 // thread priorities.
pbos12411ef2015-11-23 14:47:56 -0800298 return true;
299#else
300#ifdef WEBRTC_THREAD_RR
301 const int policy = SCHED_RR;
302#else
303 const int policy = SCHED_FIFO;
304#endif
305 const int min_prio = sched_get_priority_min(policy);
306 const int max_prio = sched_get_priority_max(policy);
307 if (min_prio == -1 || max_prio == -1) {
308 return false;
309 }
310
311 if (max_prio - min_prio <= 2)
312 return false;
313
Peter Boström97c821d2015-11-24 13:48:13 +0100314 // Convert webrtc priority to system priorities:
pbos12411ef2015-11-23 14:47:56 -0800315 sched_param param;
Peter Boström97c821d2015-11-24 13:48:13 +0100316 const int top_prio = max_prio - 1;
317 const int low_prio = min_prio + 1;
318 switch (priority) {
319 case kLowPriority:
320 param.sched_priority = low_prio;
321 break;
322 case kNormalPriority:
323 // The -1 ensures that the kHighPriority is always greater or equal to
324 // kNormalPriority.
325 param.sched_priority = (low_prio + top_prio - 1) / 2;
326 break;
327 case kHighPriority:
328 param.sched_priority = std::max(top_prio - 2, low_prio);
329 break;
330 case kHighestPriority:
331 param.sched_priority = std::max(top_prio - 1, low_prio);
332 break;
333 case kRealtimePriority:
334 param.sched_priority = top_prio;
335 break;
pbos12411ef2015-11-23 14:47:56 -0800336 }
Peter Boström97c821d2015-11-24 13:48:13 +0100337 return pthread_setschedparam(thread_, policy, &param) == 0;
pbos12411ef2015-11-23 14:47:56 -0800338#endif // defined(WEBRTC_WIN)
339}
340
tommi845afa82016-04-22 09:08:44 -0700341#if defined(WEBRTC_WIN)
342bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
343 RTC_DCHECK(thread_checker_.CalledOnValidThread());
344 RTC_DCHECK(IsRunning());
345
346 return QueueUserAPC(function, thread_, data) != FALSE;
347}
348#endif
349
Peter Boström8c38e8b2015-11-26 17:45:47 +0100350} // namespace rtc