Cleanup setting of 'sysroot' in common.gypi
[chromium-blink-merge.git] / base / threading / platform_thread_posix.cc
blob0adb92dbce50da89aa424154e3af9f3ce5b36a8d
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"
7 #include <errno.h>
8 #include <pthread.h>
9 #include <sched.h>
10 #include <sys/resource.h>
11 #include <sys/time.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"
20 #if defined(OS_LINUX)
21 #include <sys/syscall.h>
22 #elif defined(OS_ANDROID)
23 #include <sys/types.h>
24 #endif
26 namespace base {
28 void InitThreading();
29 void InitOnThread();
30 void TerminateOnThread();
31 size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
33 namespace {
35 struct ThreadParams {
36 ThreadParams()
37 : delegate(NULL), joinable(false), priority(ThreadPriority::NORMAL) {}
39 PlatformThread::Delegate* delegate;
40 bool joinable;
41 ThreadPriority priority;
44 void* ThreadFunc(void* params) {
45 base::InitOnThread();
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();
71 return NULL;
74 bool CreateThread(size_t stack_size,
75 bool joinable,
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.
87 if (!joinable)
88 pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
90 // Get a better default if available.
91 if (stack_size == 0)
92 stack_size = base::GetDefaultThreadStackSize(attributes);
94 if (stack_size > 0)
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;
102 pthread_t handle;
103 int err = pthread_create(&handle, &attributes, ThreadFunc, params.get());
104 bool success = !err;
105 if (success) {
106 // ThreadParams should be deleted on the created thread after used.
107 ignore_result(params.release());
108 } else {
109 // Value of |handle| is undefined if pthread_create fails.
110 handle = 0;
111 errno = err;
112 PLOG(ERROR) << "pthread_create";
114 *thread_handle = PlatformThreadHandle(handle);
116 pthread_attr_destroy(&attributes);
118 return success;
121 } // namespace
123 // static
124 PlatformThreadId PlatformThread::CurrentId() {
125 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
126 // into the kernel.
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)
132 return gettid();
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());
142 #endif
145 // static
146 PlatformThreadRef PlatformThread::CurrentRef() {
147 return PlatformThreadRef(pthread_self());
150 // static
151 PlatformThreadHandle PlatformThread::CurrentHandle() {
152 return PlatformThreadHandle(pthread_self());
155 // static
156 void PlatformThread::YieldCurrentThread() {
157 sched_yield();
160 // static
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;
175 // static
176 const char* PlatformThread::GetName() {
177 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
180 // static
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);
188 // static
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);
194 return result;
197 // static
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 /
201 // blocking tasks.
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)
209 // static
210 void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
211 #if defined(OS_NACL)
212 NOTIMPLEMENTED();
213 #else
214 if (internal::SetCurrentThreadPriorityForPlatform(priority))
215 return;
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)
231 // static
232 ThreadPriority PlatformThread::GetCurrentThreadPriority() {
233 #if defined(OS_NACL)
234 NOTIMPLEMENTED();
235 return ThreadPriority::NORMAL;
236 #else
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
246 errno = 0;
247 int nice_value = getpriority(PRIO_PROCESS, 0);
248 if (errno != 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)
260 } // namespace base