Extension syncing: Introduce a NeedsSync pref
[chromium-blink-merge.git] / base / threading / platform_thread_posix.cc
blob50c335720be8cf0268f2ec20d294e90cfa2726a1
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/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"
22 #if defined(OS_LINUX)
23 #include <sys/syscall.h>
24 #elif defined(OS_ANDROID)
25 #include <sys/types.h>
26 #endif
28 namespace base {
30 void InitThreading();
31 void InitOnThread();
32 void TerminateOnThread();
33 size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
35 namespace {
37 struct ThreadParams {
38 ThreadParams()
39 : delegate(NULL),
40 joinable(false),
41 priority(ThreadPriority::NORMAL),
42 handle(NULL),
43 handle_set(false, false) {
46 PlatformThread::Delegate* delegate;
47 bool joinable;
48 ThreadPriority priority;
49 PlatformThreadHandle* handle;
50 WaitableEvent handle_set;
53 void* ThreadFunc(void* params) {
54 base::InitOnThread();
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::SetCurrentThreadPriority(thread_params->priority);
64 // Stash the id in the handle so the calling thread has a complete
65 // handle, and unblock the parent thread.
66 *(thread_params->handle) = PlatformThreadHandle(pthread_self(),
67 PlatformThread::CurrentId());
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 params.handle_set.Wait();
132 CHECK_EQ(handle, thread_handle->platform_handle());
134 return success;
137 } // namespace
139 // static
140 PlatformThreadId PlatformThread::CurrentId() {
141 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
142 // into the kernel.
143 #if defined(OS_MACOSX)
144 return pthread_mach_thread_np(pthread_self());
145 #elif defined(OS_LINUX)
146 return syscall(__NR_gettid);
147 #elif defined(OS_ANDROID)
148 return gettid();
149 #elif defined(OS_SOLARIS) || defined(OS_QNX)
150 return pthread_self();
151 #elif defined(OS_NACL) && defined(__GLIBC__)
152 return pthread_self();
153 #elif defined(OS_NACL) && !defined(__GLIBC__)
154 // Pointers are 32-bits in NaCl.
155 return reinterpret_cast<int32>(pthread_self());
156 #elif defined(OS_POSIX)
157 return reinterpret_cast<int64>(pthread_self());
158 #endif
161 // static
162 PlatformThreadRef PlatformThread::CurrentRef() {
163 return PlatformThreadRef(pthread_self());
166 // static
167 PlatformThreadHandle PlatformThread::CurrentHandle() {
168 return PlatformThreadHandle(pthread_self(), CurrentId());
171 // static
172 void PlatformThread::YieldCurrentThread() {
173 sched_yield();
176 // static
177 void PlatformThread::Sleep(TimeDelta duration) {
178 struct timespec sleep_time, remaining;
180 // Break the duration into seconds and nanoseconds.
181 // NOTE: TimeDelta's microseconds are int64s while timespec's
182 // nanoseconds are longs, so this unpacking must prevent overflow.
183 sleep_time.tv_sec = duration.InSeconds();
184 duration -= TimeDelta::FromSeconds(sleep_time.tv_sec);
185 sleep_time.tv_nsec = duration.InMicroseconds() * 1000; // nanoseconds
187 while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
188 sleep_time = remaining;
191 // static
192 const char* PlatformThread::GetName() {
193 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
196 // static
197 bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
198 PlatformThreadHandle* thread_handle,
199 ThreadPriority priority) {
200 base::ThreadRestrictions::ScopedAllowWait allow_wait;
201 return CreateThread(stack_size, true, // joinable thread
202 delegate, thread_handle, priority);
205 // static
206 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
207 PlatformThreadHandle unused;
209 base::ThreadRestrictions::ScopedAllowWait allow_wait;
210 bool result = CreateThread(stack_size, false /* non-joinable thread */,
211 delegate, &unused, ThreadPriority::NORMAL);
212 return result;
215 // static
216 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
217 // Joining another thread may block the current thread for a long time, since
218 // the thread referred to by |thread_handle| may still be running long-lived /
219 // blocking tasks.
220 base::ThreadRestrictions::AssertIOAllowed();
221 CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), NULL));
224 // Mac has its own Set/GetCurrentThreadPriority() implementations.
225 #if !defined(OS_MACOSX)
227 // static
228 void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
229 #if defined(OS_NACL)
230 NOTIMPLEMENTED();
231 #else
232 if (internal::SetCurrentThreadPriorityForPlatform(priority))
233 return;
235 // setpriority(2) should change the whole thread group's (i.e. process)
236 // priority. However, as stated in the bugs section of
237 // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
238 // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
239 // attribute". Also, 0 is prefered to the current thread id since it is
240 // equivalent but makes sandboxing easier (https://crbug.com/399473).
241 const int nice_setting = internal::ThreadPriorityToNiceValue(priority);
242 if (setpriority(PRIO_PROCESS, 0, nice_setting)) {
243 DVPLOG(1) << "Failed to set nice value of thread ("
244 << PlatformThread::CurrentId() << ") to " << nice_setting;
246 #endif // defined(OS_NACL)
249 // static
250 ThreadPriority PlatformThread::GetCurrentThreadPriority() {
251 #if defined(OS_NACL)
252 NOTIMPLEMENTED();
253 return ThreadPriority::NORMAL;
254 #else
255 // Mirrors SetCurrentThreadPriority()'s implementation.
256 ThreadPriority platform_specific_priority;
257 if (internal::GetCurrentThreadPriorityForPlatform(
258 &platform_specific_priority)) {
259 return platform_specific_priority;
262 // Need to clear errno before calling getpriority():
263 // http://man7.org/linux/man-pages/man2/getpriority.2.html
264 errno = 0;
265 int nice_value = getpriority(PRIO_PROCESS, 0);
266 if (errno != 0) {
267 DVPLOG(1) << "Failed to get nice value of thread ("
268 << PlatformThread::CurrentId() << ")";
269 return ThreadPriority::NORMAL;
272 return internal::NiceValueToThreadPriority(nice_value);
273 #endif // !defined(OS_NACL)
276 #endif // !defined(OS_MACOSX)
278 } // namespace base