1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/threading/platform_thread.h"
10 #include <sys/resource.h>
13 #include "base/lazy_instance.h"
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/profiler/scoped_tracker.h"
17 #include "base/synchronization/waitable_event.h"
18 #include "base/threading/platform_thread_internal_posix.h"
19 #include "base/threading/thread_id_name_manager.h"
20 #include "base/threading/thread_restrictions.h"
21 #include "base/tracked_objects.h"
24 #include <sys/syscall.h>
25 #elif defined(OS_ANDROID)
26 #include <sys/types.h>
33 void TerminateOnThread();
34 size_t GetDefaultThreadStackSize(const pthread_attr_t
& attributes
);
42 priority(ThreadPriority::NORMAL
),
44 handle_set(false, false) {
47 PlatformThread::Delegate
* delegate
;
49 ThreadPriority priority
;
50 PlatformThreadHandle
* handle
;
51 WaitableEvent handle_set
;
54 void* ThreadFunc(void* params
) {
56 ThreadParams
* thread_params
= static_cast<ThreadParams
*>(params
);
58 PlatformThread::Delegate
* delegate
= thread_params
->delegate
;
59 if (!thread_params
->joinable
)
60 base::ThreadRestrictions::SetSingletonAllowed(false);
62 if (thread_params
->priority
!= ThreadPriority::NORMAL
)
63 PlatformThread::SetCurrentThreadPriority(thread_params
->priority
);
65 // Stash the id in the handle so the calling thread has a complete
66 // handle, and unblock the parent thread.
67 *(thread_params
->handle
) = PlatformThreadHandle(pthread_self());
68 thread_params
->handle_set
.Signal();
70 ThreadIdNameManager::GetInstance()->RegisterThread(
71 PlatformThread::CurrentHandle().platform_handle(),
72 PlatformThread::CurrentId());
74 delegate
->ThreadMain();
76 ThreadIdNameManager::GetInstance()->RemoveName(
77 PlatformThread::CurrentHandle().platform_handle(),
78 PlatformThread::CurrentId());
80 base::TerminateOnThread();
84 bool CreateThread(size_t stack_size
, bool joinable
,
85 PlatformThread::Delegate
* delegate
,
86 PlatformThreadHandle
* thread_handle
,
87 ThreadPriority priority
) {
88 base::InitThreading();
91 pthread_attr_t attributes
;
92 pthread_attr_init(&attributes
);
94 // Pthreads are joinable by default, so only specify the detached
95 // attribute if the thread should be non-joinable.
97 pthread_attr_setdetachstate(&attributes
, PTHREAD_CREATE_DETACHED
);
100 // Get a better default if available.
102 stack_size
= base::GetDefaultThreadStackSize(attributes
);
105 pthread_attr_setstacksize(&attributes
, stack_size
);
108 params
.delegate
= delegate
;
109 params
.joinable
= joinable
;
110 params
.priority
= priority
;
111 params
.handle
= thread_handle
;
114 int err
= pthread_create(&handle
,
120 // Value of |handle| is undefined if pthread_create fails.
123 PLOG(ERROR
) << "pthread_create";
126 pthread_attr_destroy(&attributes
);
128 // Don't let this call complete until the thread id
129 // is set in the handle.
131 // TODO(toyoshim): Remove this after a few days (crbug.com/495097)
132 tracked_objects::ScopedTracker
tracking_profile(
133 FROM_HERE_WITH_EXPLICIT_FUNCTION(
134 "495097 pthread_create and handle_set.Wait"));
135 params
.handle_set
.Wait();
137 CHECK_EQ(handle
, thread_handle
->platform_handle());
145 PlatformThreadId
PlatformThread::CurrentId() {
146 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
148 #if defined(OS_MACOSX)
149 return pthread_mach_thread_np(pthread_self());
150 #elif defined(OS_LINUX)
151 return syscall(__NR_gettid
);
152 #elif defined(OS_ANDROID)
154 #elif defined(OS_SOLARIS) || defined(OS_QNX)
155 return pthread_self();
156 #elif defined(OS_NACL) && defined(__GLIBC__)
157 return pthread_self();
158 #elif defined(OS_NACL) && !defined(__GLIBC__)
159 // Pointers are 32-bits in NaCl.
160 return reinterpret_cast<int32
>(pthread_self());
161 #elif defined(OS_POSIX)
162 return reinterpret_cast<int64
>(pthread_self());
167 PlatformThreadRef
PlatformThread::CurrentRef() {
168 return PlatformThreadRef(pthread_self());
172 PlatformThreadHandle
PlatformThread::CurrentHandle() {
173 return PlatformThreadHandle(pthread_self());
177 void PlatformThread::YieldCurrentThread() {
182 void PlatformThread::Sleep(TimeDelta duration
) {
183 struct timespec sleep_time
, remaining
;
185 // Break the duration into seconds and nanoseconds.
186 // NOTE: TimeDelta's microseconds are int64s while timespec's
187 // nanoseconds are longs, so this unpacking must prevent overflow.
188 sleep_time
.tv_sec
= duration
.InSeconds();
189 duration
-= TimeDelta::FromSeconds(sleep_time
.tv_sec
);
190 sleep_time
.tv_nsec
= duration
.InMicroseconds() * 1000; // nanoseconds
192 while (nanosleep(&sleep_time
, &remaining
) == -1 && errno
== EINTR
)
193 sleep_time
= remaining
;
197 const char* PlatformThread::GetName() {
198 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
202 bool PlatformThread::CreateWithPriority(size_t stack_size
, Delegate
* delegate
,
203 PlatformThreadHandle
* thread_handle
,
204 ThreadPriority priority
) {
205 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
206 return CreateThread(stack_size
, true, // joinable thread
207 delegate
, thread_handle
, priority
);
211 bool PlatformThread::CreateNonJoinable(size_t stack_size
, Delegate
* delegate
) {
212 PlatformThreadHandle unused
;
214 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
215 bool result
= CreateThread(stack_size
, false /* non-joinable thread */,
216 delegate
, &unused
, ThreadPriority::NORMAL
);
221 void PlatformThread::Join(PlatformThreadHandle thread_handle
) {
222 // Joining another thread may block the current thread for a long time, since
223 // the thread referred to by |thread_handle| may still be running long-lived /
225 base::ThreadRestrictions::AssertIOAllowed();
226 CHECK_EQ(0, pthread_join(thread_handle
.platform_handle(), NULL
));
229 // Mac has its own Set/GetCurrentThreadPriority() implementations.
230 #if !defined(OS_MACOSX)
233 void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority
) {
237 if (internal::SetCurrentThreadPriorityForPlatform(priority
))
240 // setpriority(2) should change the whole thread group's (i.e. process)
241 // priority. However, as stated in the bugs section of
242 // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
243 // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
244 // attribute". Also, 0 is prefered to the current thread id since it is
245 // equivalent but makes sandboxing easier (https://crbug.com/399473).
246 const int nice_setting
= internal::ThreadPriorityToNiceValue(priority
);
247 if (setpriority(PRIO_PROCESS
, 0, nice_setting
)) {
248 DVPLOG(1) << "Failed to set nice value of thread ("
249 << PlatformThread::CurrentId() << ") to " << nice_setting
;
251 #endif // defined(OS_NACL)
255 ThreadPriority
PlatformThread::GetCurrentThreadPriority() {
258 return ThreadPriority::NORMAL
;
260 // Mirrors SetCurrentThreadPriority()'s implementation.
261 ThreadPriority platform_specific_priority
;
262 if (internal::GetCurrentThreadPriorityForPlatform(
263 &platform_specific_priority
)) {
264 return platform_specific_priority
;
267 // Need to clear errno before calling getpriority():
268 // http://man7.org/linux/man-pages/man2/getpriority.2.html
270 int nice_value
= getpriority(PRIO_PROCESS
, 0);
272 DVPLOG(1) << "Failed to get nice value of thread ("
273 << PlatformThread::CurrentId() << ")";
274 return ThreadPriority::NORMAL
;
277 return internal::NiceValueToThreadPriority(nice_value
);
278 #endif // !defined(OS_NACL)
281 #endif // !defined(OS_MACOSX)