base/threading: remove ScopedTracker placed for experiments
[chromium-blink-merge.git] / base / threading / platform_thread_posix.cc
blob61d75861d3f2e89f7a2b58b76a4a9a8a755b5f5a
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 =
104 pthread_create(&handle, &attributes, ThreadFunc, params.get());
105 bool success = !err;
106 if (success) {
107 // ThreadParams should be deleted on the created thread after used.
108 ignore_result(params.release());
109 } else {
110 // Value of |handle| is undefined if pthread_create fails.
111 handle = 0;
112 errno = err;
113 PLOG(ERROR) << "pthread_create";
115 *thread_handle = PlatformThreadHandle(handle);
117 pthread_attr_destroy(&attributes);
119 return success;
122 } // namespace
124 // static
125 PlatformThreadId PlatformThread::CurrentId() {
126 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
127 // into the kernel.
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)
133 return gettid();
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());
143 #endif
146 // static
147 PlatformThreadRef PlatformThread::CurrentRef() {
148 return PlatformThreadRef(pthread_self());
151 // static
152 PlatformThreadHandle PlatformThread::CurrentHandle() {
153 return PlatformThreadHandle(pthread_self());
156 // static
157 void PlatformThread::YieldCurrentThread() {
158 sched_yield();
161 // static
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;
176 // static
177 const char* PlatformThread::GetName() {
178 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
181 // static
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);
189 // static
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);
195 return result;
198 // static
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 /
202 // blocking tasks.
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)
210 // static
211 void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
212 #if defined(OS_NACL)
213 NOTIMPLEMENTED();
214 #else
215 if (internal::SetCurrentThreadPriorityForPlatform(priority))
216 return;
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)
232 // static
233 ThreadPriority PlatformThread::GetCurrentThreadPriority() {
234 #if defined(OS_NACL)
235 NOTIMPLEMENTED();
236 return ThreadPriority::NORMAL;
237 #else
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
247 errno = 0;
248 int nice_value = getpriority(PRIO_PROCESS, 0);
249 if (errno != 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)
261 } // namespace base