Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / base / threading / platform_thread_posix.cc
blob8e3f365c71f4a4464a428f68918f54ee2b09a7d0
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/profiler/scoped_tracker.h"
17 #include "base/synchronization/waitable_event.h"
18 #include "base/threading/platform_thread_internal_posix.h"
19 #include "base/threading/thread_id_name_manager.h"
20 #include "base/threading/thread_restrictions.h"
21 #include "base/tracked_objects.h"
23 #if defined(OS_LINUX)
24 #include <sys/syscall.h>
25 #elif defined(OS_ANDROID)
26 #include <sys/types.h>
27 #endif
29 namespace base {
31 void InitThreading();
32 void InitOnThread();
33 void TerminateOnThread();
34 size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
36 namespace {
38 struct ThreadParams {
39 ThreadParams()
40 : delegate(NULL),
41 joinable(false),
42 priority(ThreadPriority::NORMAL),
43 handle(NULL),
44 handle_set(false, false) {
47 PlatformThread::Delegate* delegate;
48 bool joinable;
49 ThreadPriority priority;
50 PlatformThreadHandle* handle;
51 WaitableEvent handle_set;
54 void* ThreadFunc(void* params) {
55 base::InitOnThread();
56 ThreadParams* thread_params = static_cast<ThreadParams*>(params);
58 PlatformThread::Delegate* delegate = thread_params->delegate;
59 if (!thread_params->joinable)
60 base::ThreadRestrictions::SetSingletonAllowed(false);
62 if (thread_params->priority != ThreadPriority::NORMAL)
63 PlatformThread::SetCurrentThreadPriority(thread_params->priority);
65 // Stash the id in the handle so the calling thread has a complete
66 // handle, and unblock the parent thread.
67 *(thread_params->handle) = PlatformThreadHandle(pthread_self());
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();
81 return NULL;
84 bool CreateThread(size_t stack_size, bool joinable,
85 PlatformThread::Delegate* delegate,
86 PlatformThreadHandle* thread_handle,
87 ThreadPriority priority) {
88 base::InitThreading();
90 bool success = false;
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.
96 if (!joinable) {
97 pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
100 // Get a better default if available.
101 if (stack_size == 0)
102 stack_size = base::GetDefaultThreadStackSize(attributes);
104 if (stack_size > 0)
105 pthread_attr_setstacksize(&attributes, stack_size);
107 ThreadParams params;
108 params.delegate = delegate;
109 params.joinable = joinable;
110 params.priority = priority;
111 params.handle = thread_handle;
113 pthread_t handle;
114 int err = pthread_create(&handle,
115 &attributes,
116 ThreadFunc,
117 &params);
118 success = !err;
119 if (!success) {
120 // Value of |handle| is undefined if pthread_create fails.
121 handle = 0;
122 errno = err;
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.
130 if (success) {
131 // TODO(toyoshim): Remove this after a few days (crbug.com/495097)
132 tracked_objects::ScopedTracker tracking_profile(
133 FROM_HERE_WITH_EXPLICIT_FUNCTION(
134 "495097 pthread_create and handle_set.Wait"));
135 params.handle_set.Wait();
137 CHECK_EQ(handle, thread_handle->platform_handle());
139 return success;
142 } // namespace
144 // static
145 PlatformThreadId PlatformThread::CurrentId() {
146 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
147 // into the kernel.
148 #if defined(OS_MACOSX)
149 return pthread_mach_thread_np(pthread_self());
150 #elif defined(OS_LINUX)
151 return syscall(__NR_gettid);
152 #elif defined(OS_ANDROID)
153 return gettid();
154 #elif defined(OS_SOLARIS) || defined(OS_QNX)
155 return pthread_self();
156 #elif defined(OS_NACL) && defined(__GLIBC__)
157 return pthread_self();
158 #elif defined(OS_NACL) && !defined(__GLIBC__)
159 // Pointers are 32-bits in NaCl.
160 return reinterpret_cast<int32>(pthread_self());
161 #elif defined(OS_POSIX)
162 return reinterpret_cast<int64>(pthread_self());
163 #endif
166 // static
167 PlatformThreadRef PlatformThread::CurrentRef() {
168 return PlatformThreadRef(pthread_self());
171 // static
172 PlatformThreadHandle PlatformThread::CurrentHandle() {
173 return PlatformThreadHandle(pthread_self());
176 // static
177 void PlatformThread::YieldCurrentThread() {
178 sched_yield();
181 // static
182 void PlatformThread::Sleep(TimeDelta duration) {
183 struct timespec sleep_time, remaining;
185 // Break the duration into seconds and nanoseconds.
186 // NOTE: TimeDelta's microseconds are int64s while timespec's
187 // nanoseconds are longs, so this unpacking must prevent overflow.
188 sleep_time.tv_sec = duration.InSeconds();
189 duration -= TimeDelta::FromSeconds(sleep_time.tv_sec);
190 sleep_time.tv_nsec = duration.InMicroseconds() * 1000; // nanoseconds
192 while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
193 sleep_time = remaining;
196 // static
197 const char* PlatformThread::GetName() {
198 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
201 // static
202 bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
203 PlatformThreadHandle* thread_handle,
204 ThreadPriority priority) {
205 base::ThreadRestrictions::ScopedAllowWait allow_wait;
206 return CreateThread(stack_size, true, // joinable thread
207 delegate, thread_handle, priority);
210 // static
211 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
212 PlatformThreadHandle unused;
214 base::ThreadRestrictions::ScopedAllowWait allow_wait;
215 bool result = CreateThread(stack_size, false /* non-joinable thread */,
216 delegate, &unused, ThreadPriority::NORMAL);
217 return result;
220 // static
221 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
222 // Joining another thread may block the current thread for a long time, since
223 // the thread referred to by |thread_handle| may still be running long-lived /
224 // blocking tasks.
225 base::ThreadRestrictions::AssertIOAllowed();
226 CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), NULL));
229 // Mac has its own Set/GetCurrentThreadPriority() implementations.
230 #if !defined(OS_MACOSX)
232 // static
233 void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
234 #if defined(OS_NACL)
235 NOTIMPLEMENTED();
236 #else
237 if (internal::SetCurrentThreadPriorityForPlatform(priority))
238 return;
240 // setpriority(2) should change the whole thread group's (i.e. process)
241 // priority. However, as stated in the bugs section of
242 // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
243 // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
244 // attribute". Also, 0 is prefered to the current thread id since it is
245 // equivalent but makes sandboxing easier (https://crbug.com/399473).
246 const int nice_setting = internal::ThreadPriorityToNiceValue(priority);
247 if (setpriority(PRIO_PROCESS, 0, nice_setting)) {
248 DVPLOG(1) << "Failed to set nice value of thread ("
249 << PlatformThread::CurrentId() << ") to " << nice_setting;
251 #endif // defined(OS_NACL)
254 // static
255 ThreadPriority PlatformThread::GetCurrentThreadPriority() {
256 #if defined(OS_NACL)
257 NOTIMPLEMENTED();
258 return ThreadPriority::NORMAL;
259 #else
260 // Mirrors SetCurrentThreadPriority()'s implementation.
261 ThreadPriority platform_specific_priority;
262 if (internal::GetCurrentThreadPriorityForPlatform(
263 &platform_specific_priority)) {
264 return platform_specific_priority;
267 // Need to clear errno before calling getpriority():
268 // http://man7.org/linux/man-pages/man2/getpriority.2.html
269 errno = 0;
270 int nice_value = getpriority(PRIO_PROCESS, 0);
271 if (errno != 0) {
272 DVPLOG(1) << "Failed to get nice value of thread ("
273 << PlatformThread::CurrentId() << ")";
274 return ThreadPriority::NORMAL;
277 return internal::NiceValueToThreadPriority(nice_value);
278 #endif // !defined(OS_NACL)
281 #endif // !defined(OS_MACOSX)
283 } // namespace base