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
;
103 int err
= pthread_create(&handle
, &attributes
, ThreadFunc
, params
.get());
106 // ThreadParams should be deleted on the created thread after used.
107 ignore_result(params
.release());
109 // Value of |handle| is undefined if pthread_create fails.
112 PLOG(ERROR
) << "pthread_create";
114 *thread_handle
= PlatformThreadHandle(handle
);
116 pthread_attr_destroy(&attributes
);
124 PlatformThreadId
PlatformThread::CurrentId() {
125 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
127 #if defined(OS_MACOSX)
128 return pthread_mach_thread_np(pthread_self());
129 #elif defined(OS_LINUX)
130 return syscall(__NR_gettid
);
131 #elif defined(OS_ANDROID)
133 #elif defined(OS_SOLARIS) || defined(OS_QNX)
134 return pthread_self();
135 #elif defined(OS_NACL) && defined(__GLIBC__)
136 return pthread_self();
137 #elif defined(OS_NACL) && !defined(__GLIBC__)
138 // Pointers are 32-bits in NaCl.
139 return reinterpret_cast<int32
>(pthread_self());
140 #elif defined(OS_POSIX)
141 return reinterpret_cast<int64
>(pthread_self());
146 PlatformThreadRef
PlatformThread::CurrentRef() {
147 return PlatformThreadRef(pthread_self());
151 PlatformThreadHandle
PlatformThread::CurrentHandle() {
152 return PlatformThreadHandle(pthread_self());
156 void PlatformThread::YieldCurrentThread() {
161 void PlatformThread::Sleep(TimeDelta duration
) {
162 struct timespec sleep_time
, remaining
;
164 // Break the duration into seconds and nanoseconds.
165 // NOTE: TimeDelta's microseconds are int64s while timespec's
166 // nanoseconds are longs, so this unpacking must prevent overflow.
167 sleep_time
.tv_sec
= duration
.InSeconds();
168 duration
-= TimeDelta::FromSeconds(sleep_time
.tv_sec
);
169 sleep_time
.tv_nsec
= duration
.InMicroseconds() * 1000; // nanoseconds
171 while (nanosleep(&sleep_time
, &remaining
) == -1 && errno
== EINTR
)
172 sleep_time
= remaining
;
176 const char* PlatformThread::GetName() {
177 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
181 bool PlatformThread::CreateWithPriority(size_t stack_size
, Delegate
* delegate
,
182 PlatformThreadHandle
* thread_handle
,
183 ThreadPriority priority
) {
184 return CreateThread(stack_size
, true, // joinable thread
185 delegate
, thread_handle
, priority
);
189 bool PlatformThread::CreateNonJoinable(size_t stack_size
, Delegate
* delegate
) {
190 PlatformThreadHandle unused
;
192 bool result
= CreateThread(stack_size
, false /* non-joinable thread */,
193 delegate
, &unused
, ThreadPriority::NORMAL
);
198 void PlatformThread::Join(PlatformThreadHandle thread_handle
) {
199 // Joining another thread may block the current thread for a long time, since
200 // the thread referred to by |thread_handle| may still be running long-lived /
202 base::ThreadRestrictions::AssertIOAllowed();
203 CHECK_EQ(0, pthread_join(thread_handle
.platform_handle(), NULL
));
206 // Mac has its own Set/GetCurrentThreadPriority() implementations.
207 #if !defined(OS_MACOSX)
210 void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority
) {
214 if (internal::SetCurrentThreadPriorityForPlatform(priority
))
217 // setpriority(2) should change the whole thread group's (i.e. process)
218 // priority. However, as stated in the bugs section of
219 // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
220 // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
221 // attribute". Also, 0 is prefered to the current thread id since it is
222 // equivalent but makes sandboxing easier (https://crbug.com/399473).
223 const int nice_setting
= internal::ThreadPriorityToNiceValue(priority
);
224 if (setpriority(PRIO_PROCESS
, 0, nice_setting
)) {
225 DVPLOG(1) << "Failed to set nice value of thread ("
226 << PlatformThread::CurrentId() << ") to " << nice_setting
;
228 #endif // defined(OS_NACL)
232 ThreadPriority
PlatformThread::GetCurrentThreadPriority() {
235 return ThreadPriority::NORMAL
;
237 // Mirrors SetCurrentThreadPriority()'s implementation.
238 ThreadPriority platform_specific_priority
;
239 if (internal::GetCurrentThreadPriorityForPlatform(
240 &platform_specific_priority
)) {
241 return platform_specific_priority
;
244 // Need to clear errno before calling getpriority():
245 // http://man7.org/linux/man-pages/man2/getpriority.2.html
247 int nice_value
= getpriority(PRIO_PROCESS
, 0);
249 DVPLOG(1) << "Failed to get nice value of thread ("
250 << PlatformThread::CurrentId() << ")";
251 return ThreadPriority::NORMAL
;
254 return internal::NiceValueToThreadPriority(nice_value
);
255 #endif // !defined(OS_NACL)
258 #endif // !defined(OS_MACOSX)