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/synchronization/waitable_event.h"
17 #include "base/threading/platform_thread_internal_posix.h"
18 #include "base/threading/thread_id_name_manager.h"
19 #include "base/threading/thread_restrictions.h"
20 #include "base/tracked_objects.h"
23 #include <sys/syscall.h>
24 #elif defined(OS_ANDROID)
25 #include <sys/types.h>
32 void TerminateOnThread();
33 size_t GetDefaultThreadStackSize(const pthread_attr_t
& attributes
);
41 priority(ThreadPriority::NORMAL
),
43 handle_set(false, false) {
46 PlatformThread::Delegate
* delegate
;
48 ThreadPriority priority
;
49 PlatformThreadHandle
* handle
;
50 WaitableEvent handle_set
;
53 void* ThreadFunc(void* params
) {
55 ThreadParams
* thread_params
= static_cast<ThreadParams
*>(params
);
57 PlatformThread::Delegate
* delegate
= thread_params
->delegate
;
58 if (!thread_params
->joinable
)
59 base::ThreadRestrictions::SetSingletonAllowed(false);
61 if (thread_params
->priority
!= ThreadPriority::NORMAL
)
62 PlatformThread::SetCurrentThreadPriority(thread_params
->priority
);
64 // Stash the id in the handle so the calling thread has a complete
65 // handle, and unblock the parent thread.
66 *(thread_params
->handle
) = PlatformThreadHandle(pthread_self(),
67 PlatformThread::CurrentId());
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 params
.handle_set
.Wait();
132 CHECK_EQ(handle
, thread_handle
->platform_handle());
140 PlatformThreadId
PlatformThread::CurrentId() {
141 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
143 #if defined(OS_MACOSX)
144 return pthread_mach_thread_np(pthread_self());
145 #elif defined(OS_LINUX)
146 return syscall(__NR_gettid
);
147 #elif defined(OS_ANDROID)
149 #elif defined(OS_SOLARIS) || defined(OS_QNX)
150 return pthread_self();
151 #elif defined(OS_NACL) && defined(__GLIBC__)
152 return pthread_self();
153 #elif defined(OS_NACL) && !defined(__GLIBC__)
154 // Pointers are 32-bits in NaCl.
155 return reinterpret_cast<int32
>(pthread_self());
156 #elif defined(OS_POSIX)
157 return reinterpret_cast<int64
>(pthread_self());
162 PlatformThreadRef
PlatformThread::CurrentRef() {
163 return PlatformThreadRef(pthread_self());
167 PlatformThreadHandle
PlatformThread::CurrentHandle() {
168 return PlatformThreadHandle(pthread_self(), CurrentId());
172 void PlatformThread::YieldCurrentThread() {
177 void PlatformThread::Sleep(TimeDelta duration
) {
178 struct timespec sleep_time
, remaining
;
180 // Break the duration into seconds and nanoseconds.
181 // NOTE: TimeDelta's microseconds are int64s while timespec's
182 // nanoseconds are longs, so this unpacking must prevent overflow.
183 sleep_time
.tv_sec
= duration
.InSeconds();
184 duration
-= TimeDelta::FromSeconds(sleep_time
.tv_sec
);
185 sleep_time
.tv_nsec
= duration
.InMicroseconds() * 1000; // nanoseconds
187 while (nanosleep(&sleep_time
, &remaining
) == -1 && errno
== EINTR
)
188 sleep_time
= remaining
;
192 const char* PlatformThread::GetName() {
193 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
197 bool PlatformThread::CreateWithPriority(size_t stack_size
, Delegate
* delegate
,
198 PlatformThreadHandle
* thread_handle
,
199 ThreadPriority priority
) {
200 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
201 return CreateThread(stack_size
, true, // joinable thread
202 delegate
, thread_handle
, priority
);
206 bool PlatformThread::CreateNonJoinable(size_t stack_size
, Delegate
* delegate
) {
207 PlatformThreadHandle unused
;
209 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
210 bool result
= CreateThread(stack_size
, false /* non-joinable thread */,
211 delegate
, &unused
, ThreadPriority::NORMAL
);
216 void PlatformThread::Join(PlatformThreadHandle thread_handle
) {
217 // Joining another thread may block the current thread for a long time, since
218 // the thread referred to by |thread_handle| may still be running long-lived /
220 base::ThreadRestrictions::AssertIOAllowed();
221 CHECK_EQ(0, pthread_join(thread_handle
.platform_handle(), NULL
));
224 // Mac has its own Set/GetCurrentThreadPriority() implementations.
225 #if !defined(OS_MACOSX)
228 void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority
) {
232 if (internal::SetCurrentThreadPriorityForPlatform(priority
))
235 // setpriority(2) should change the whole thread group's (i.e. process)
236 // priority. However, as stated in the bugs section of
237 // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
238 // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
239 // attribute". Also, 0 is prefered to the current thread id since it is
240 // equivalent but makes sandboxing easier (https://crbug.com/399473).
241 const int nice_setting
= internal::ThreadPriorityToNiceValue(priority
);
242 if (setpriority(PRIO_PROCESS
, 0, nice_setting
)) {
243 DVPLOG(1) << "Failed to set nice value of thread ("
244 << PlatformThread::CurrentId() << ") to " << nice_setting
;
246 #endif // defined(OS_NACL)
250 ThreadPriority
PlatformThread::GetCurrentThreadPriority() {
253 return ThreadPriority::NORMAL
;
255 // Mirrors SetCurrentThreadPriority()'s implementation.
256 ThreadPriority platform_specific_priority
;
257 if (internal::GetCurrentThreadPriorityForPlatform(
258 &platform_specific_priority
)) {
259 return platform_specific_priority
;
262 // Need to clear errno before calling getpriority():
263 // http://man7.org/linux/man-pages/man2/getpriority.2.html
265 int nice_value
= getpriority(PRIO_PROCESS
, 0);
267 DVPLOG(1) << "Failed to get nice value of thread ("
268 << PlatformThread::CurrentId() << ")";
269 return ThreadPriority::NORMAL
;
272 return internal::NiceValueToThreadPriority(nice_value
);
273 #endif // !defined(OS_NACL)
276 #endif // !defined(OS_MACOSX)