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/threading/platform_thread_internal_posix.h"
17 #include "base/threading/thread_id_name_manager.h"
18 #include "base/threading/thread_restrictions.h"
21 #include <sys/syscall.h>
22 #elif defined(OS_ANDROID)
23 #include <sys/types.h>
30 void TerminateOnThread();
31 size_t GetDefaultThreadStackSize(const pthread_attr_t
& attributes
);
37 : delegate(NULL
), joinable(false), priority(ThreadPriority::NORMAL
) {}
39 PlatformThread::Delegate
* delegate
;
41 ThreadPriority priority
;
44 void* ThreadFunc(void* params
) {
47 PlatformThread::Delegate
* delegate
= nullptr;
50 scoped_ptr
<ThreadParams
> thread_params(static_cast<ThreadParams
*>(params
));
52 delegate
= thread_params
->delegate
;
53 if (!thread_params
->joinable
)
54 base::ThreadRestrictions::SetSingletonAllowed(false);
56 if (thread_params
->priority
!= ThreadPriority::NORMAL
)
57 PlatformThread::SetCurrentThreadPriority(thread_params
->priority
);
60 ThreadIdNameManager::GetInstance()->RegisterThread(
61 PlatformThread::CurrentHandle().platform_handle(),
62 PlatformThread::CurrentId());
64 delegate
->ThreadMain();
66 ThreadIdNameManager::GetInstance()->RemoveName(
67 PlatformThread::CurrentHandle().platform_handle(),
68 PlatformThread::CurrentId());
70 base::TerminateOnThread();
74 bool CreateThread(size_t stack_size
,
76 PlatformThread::Delegate
* delegate
,
77 PlatformThreadHandle
* thread_handle
,
78 ThreadPriority priority
) {
79 DCHECK(thread_handle
);
80 base::InitThreading();
82 pthread_attr_t attributes
;
83 pthread_attr_init(&attributes
);
85 // Pthreads are joinable by default, so only specify the detached
86 // attribute if the thread should be non-joinable.
88 pthread_attr_setdetachstate(&attributes
, PTHREAD_CREATE_DETACHED
);
90 // Get a better default if available.
92 stack_size
= base::GetDefaultThreadStackSize(attributes
);
95 pthread_attr_setstacksize(&attributes
, stack_size
);
97 scoped_ptr
<ThreadParams
> params(new ThreadParams
);
98 params
->delegate
= delegate
;
99 params
->joinable
= joinable
;
100 params
->priority
= priority
;
104 pthread_create(&handle
, &attributes
, ThreadFunc
, params
.get());
107 // ThreadParams should be deleted on the created thread after used.
108 ignore_result(params
.release());
110 // Value of |handle| is undefined if pthread_create fails.
113 PLOG(ERROR
) << "pthread_create";
115 *thread_handle
= PlatformThreadHandle(handle
);
117 pthread_attr_destroy(&attributes
);
125 PlatformThreadId
PlatformThread::CurrentId() {
126 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
128 #if defined(OS_MACOSX)
129 return pthread_mach_thread_np(pthread_self());
130 #elif defined(OS_LINUX)
131 return syscall(__NR_gettid
);
132 #elif defined(OS_ANDROID)
134 #elif defined(OS_SOLARIS) || defined(OS_QNX)
135 return pthread_self();
136 #elif defined(OS_NACL) && defined(__GLIBC__)
137 return pthread_self();
138 #elif defined(OS_NACL) && !defined(__GLIBC__)
139 // Pointers are 32-bits in NaCl.
140 return reinterpret_cast<int32
>(pthread_self());
141 #elif defined(OS_POSIX)
142 return reinterpret_cast<int64
>(pthread_self());
147 PlatformThreadRef
PlatformThread::CurrentRef() {
148 return PlatformThreadRef(pthread_self());
152 PlatformThreadHandle
PlatformThread::CurrentHandle() {
153 return PlatformThreadHandle(pthread_self());
157 void PlatformThread::YieldCurrentThread() {
162 void PlatformThread::Sleep(TimeDelta duration
) {
163 struct timespec sleep_time
, remaining
;
165 // Break the duration into seconds and nanoseconds.
166 // NOTE: TimeDelta's microseconds are int64s while timespec's
167 // nanoseconds are longs, so this unpacking must prevent overflow.
168 sleep_time
.tv_sec
= duration
.InSeconds();
169 duration
-= TimeDelta::FromSeconds(sleep_time
.tv_sec
);
170 sleep_time
.tv_nsec
= duration
.InMicroseconds() * 1000; // nanoseconds
172 while (nanosleep(&sleep_time
, &remaining
) == -1 && errno
== EINTR
)
173 sleep_time
= remaining
;
177 const char* PlatformThread::GetName() {
178 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
182 bool PlatformThread::CreateWithPriority(size_t stack_size
, Delegate
* delegate
,
183 PlatformThreadHandle
* thread_handle
,
184 ThreadPriority priority
) {
185 return CreateThread(stack_size
, true, // joinable thread
186 delegate
, thread_handle
, priority
);
190 bool PlatformThread::CreateNonJoinable(size_t stack_size
, Delegate
* delegate
) {
191 PlatformThreadHandle unused
;
193 bool result
= CreateThread(stack_size
, false /* non-joinable thread */,
194 delegate
, &unused
, ThreadPriority::NORMAL
);
199 void PlatformThread::Join(PlatformThreadHandle thread_handle
) {
200 // Joining another thread may block the current thread for a long time, since
201 // the thread referred to by |thread_handle| may still be running long-lived /
203 base::ThreadRestrictions::AssertIOAllowed();
204 CHECK_EQ(0, pthread_join(thread_handle
.platform_handle(), NULL
));
207 // Mac has its own Set/GetCurrentThreadPriority() implementations.
208 #if !defined(OS_MACOSX)
211 void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority
) {
215 if (internal::SetCurrentThreadPriorityForPlatform(priority
))
218 // setpriority(2) should change the whole thread group's (i.e. process)
219 // priority. However, as stated in the bugs section of
220 // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
221 // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
222 // attribute". Also, 0 is prefered to the current thread id since it is
223 // equivalent but makes sandboxing easier (https://crbug.com/399473).
224 const int nice_setting
= internal::ThreadPriorityToNiceValue(priority
);
225 if (setpriority(PRIO_PROCESS
, 0, nice_setting
)) {
226 DVPLOG(1) << "Failed to set nice value of thread ("
227 << PlatformThread::CurrentId() << ") to " << nice_setting
;
229 #endif // defined(OS_NACL)
233 ThreadPriority
PlatformThread::GetCurrentThreadPriority() {
236 return ThreadPriority::NORMAL
;
238 // Mirrors SetCurrentThreadPriority()'s implementation.
239 ThreadPriority platform_specific_priority
;
240 if (internal::GetCurrentThreadPriorityForPlatform(
241 &platform_specific_priority
)) {
242 return platform_specific_priority
;
245 // Need to clear errno before calling getpriority():
246 // http://man7.org/linux/man-pages/man2/getpriority.2.html
248 int nice_value
= getpriority(PRIO_PROCESS
, 0);
250 DVPLOG(1) << "Failed to get nice value of thread ("
251 << PlatformThread::CurrentId() << ")";
252 return ThreadPriority::NORMAL
;
255 return internal::NiceValueToThreadPriority(nice_value
);
256 #endif // !defined(OS_NACL)
259 #endif // !defined(OS_MACOSX)