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::SetThreadPriority(PlatformThread::CurrentHandle(),
63 thread_params
->priority
);
66 // Stash the id in the handle so the calling thread has a complete
67 // handle, and unblock the parent thread.
68 *(thread_params
->handle
) = PlatformThreadHandle(pthread_self(),
69 PlatformThread::CurrentId());
70 thread_params
->handle_set
.Signal();
72 ThreadIdNameManager::GetInstance()->RegisterThread(
73 PlatformThread::CurrentHandle().platform_handle(),
74 PlatformThread::CurrentId());
76 delegate
->ThreadMain();
78 ThreadIdNameManager::GetInstance()->RemoveName(
79 PlatformThread::CurrentHandle().platform_handle(),
80 PlatformThread::CurrentId());
82 base::TerminateOnThread();
86 bool CreateThread(size_t stack_size
, bool joinable
,
87 PlatformThread::Delegate
* delegate
,
88 PlatformThreadHandle
* thread_handle
,
89 ThreadPriority priority
) {
90 base::InitThreading();
93 pthread_attr_t attributes
;
94 pthread_attr_init(&attributes
);
96 // Pthreads are joinable by default, so only specify the detached
97 // attribute if the thread should be non-joinable.
99 pthread_attr_setdetachstate(&attributes
, PTHREAD_CREATE_DETACHED
);
102 // Get a better default if available.
104 stack_size
= base::GetDefaultThreadStackSize(attributes
);
107 pthread_attr_setstacksize(&attributes
, stack_size
);
110 params
.delegate
= delegate
;
111 params
.joinable
= joinable
;
112 params
.priority
= priority
;
113 params
.handle
= thread_handle
;
116 int err
= pthread_create(&handle
,
122 // Value of |handle| is undefined if pthread_create fails.
125 PLOG(ERROR
) << "pthread_create";
128 pthread_attr_destroy(&attributes
);
130 // Don't let this call complete until the thread id
131 // is set in the handle.
133 params
.handle_set
.Wait();
134 CHECK_EQ(handle
, thread_handle
->platform_handle());
142 PlatformThreadId
PlatformThread::CurrentId() {
143 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
145 #if defined(OS_MACOSX)
146 return pthread_mach_thread_np(pthread_self());
147 #elif defined(OS_LINUX)
148 return syscall(__NR_gettid
);
149 #elif defined(OS_ANDROID)
151 #elif defined(OS_SOLARIS) || defined(OS_QNX)
152 return pthread_self();
153 #elif defined(OS_NACL) && defined(__GLIBC__)
154 return pthread_self();
155 #elif defined(OS_NACL) && !defined(__GLIBC__)
156 // Pointers are 32-bits in NaCl.
157 return reinterpret_cast<int32
>(pthread_self());
158 #elif defined(OS_POSIX)
159 return reinterpret_cast<int64
>(pthread_self());
164 PlatformThreadRef
PlatformThread::CurrentRef() {
165 return PlatformThreadRef(pthread_self());
169 PlatformThreadHandle
PlatformThread::CurrentHandle() {
170 return PlatformThreadHandle(pthread_self(), CurrentId());
174 void PlatformThread::YieldCurrentThread() {
179 void PlatformThread::Sleep(TimeDelta duration
) {
180 struct timespec sleep_time
, remaining
;
182 // Break the duration into seconds and nanoseconds.
183 // NOTE: TimeDelta's microseconds are int64s while timespec's
184 // nanoseconds are longs, so this unpacking must prevent overflow.
185 sleep_time
.tv_sec
= duration
.InSeconds();
186 duration
-= TimeDelta::FromSeconds(sleep_time
.tv_sec
);
187 sleep_time
.tv_nsec
= duration
.InMicroseconds() * 1000; // nanoseconds
189 while (nanosleep(&sleep_time
, &remaining
) == -1 && errno
== EINTR
)
190 sleep_time
= remaining
;
194 const char* PlatformThread::GetName() {
195 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
199 bool PlatformThread::Create(size_t stack_size
, Delegate
* delegate
,
200 PlatformThreadHandle
* thread_handle
) {
201 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
202 return CreateThread(stack_size
, true /* joinable thread */,
203 delegate
, thread_handle
, ThreadPriority::NORMAL
);
207 bool PlatformThread::CreateWithPriority(size_t stack_size
, Delegate
* delegate
,
208 PlatformThreadHandle
* thread_handle
,
209 ThreadPriority priority
) {
210 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
211 return CreateThread(stack_size
, true, // joinable thread
212 delegate
, thread_handle
, priority
);
216 bool PlatformThread::CreateNonJoinable(size_t stack_size
, Delegate
* delegate
) {
217 PlatformThreadHandle unused
;
219 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
220 bool result
= CreateThread(stack_size
, false /* non-joinable thread */,
221 delegate
, &unused
, ThreadPriority::NORMAL
);
226 void PlatformThread::Join(PlatformThreadHandle thread_handle
) {
227 // Joining another thread may block the current thread for a long time, since
228 // the thread referred to by |thread_handle| may still be running long-lived /
230 base::ThreadRestrictions::AssertIOAllowed();
231 CHECK_EQ(0, pthread_join(thread_handle
.platform_handle(), NULL
));
234 // Mac has its own Set/GetThreadPriority() implementations.
235 #if !defined(OS_MACOSX)
238 void PlatformThread::SetThreadPriority(PlatformThreadHandle handle
,
239 ThreadPriority priority
) {
243 if (internal::SetThreadPriorityForPlatform(handle
, priority
))
246 // setpriority(2) should change the whole thread group's (i.e. process)
247 // priority. However, as stated in the bugs section of
248 // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
249 // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
250 // attribute". Also, 0 is prefered to the current thread id since it is
251 // equivalent but makes sandboxing easier (https://crbug.com/399473).
252 DCHECK_NE(handle
.id(), kInvalidThreadId
);
253 const int nice_setting
= internal::ThreadPriorityToNiceValue(priority
);
254 const PlatformThreadId current_id
= PlatformThread::CurrentId();
255 if (setpriority(PRIO_PROCESS
, handle
.id() == current_id
? 0 : handle
.id(),
257 DVPLOG(1) << "Failed to set nice value of thread (" << handle
.id()
258 << ") to " << nice_setting
;
260 #endif // defined(OS_NACL)
264 ThreadPriority
PlatformThread::GetThreadPriority(PlatformThreadHandle handle
) {
267 return ThreadPriority::NORMAL
;
269 // Mirrors SetThreadPriority()'s implementation.
270 ThreadPriority platform_specific_priority
;
271 if (internal::GetThreadPriorityForPlatform(handle
,
272 &platform_specific_priority
)) {
273 return platform_specific_priority
;
276 DCHECK_NE(handle
.id(), kInvalidThreadId
);
277 const PlatformThreadId current_id
= PlatformThread::CurrentId();
278 // Need to clear errno before calling getpriority():
279 // http://man7.org/linux/man-pages/man2/getpriority.2.html
282 getpriority(PRIO_PROCESS
, handle
.id() == current_id
? 0 : handle
.id());
284 DVPLOG(1) << "Failed to get nice value of thread (" << handle
.id() << ")";
285 return ThreadPriority::NORMAL
;
288 return internal::NiceValueToThreadPriority(nice_value
);
289 #endif // !defined(OS_NACL)
292 #endif // !defined(OS_MACOSX)