Don't preload rarely seen large images
[chromium-blink-merge.git] / base / threading / platform_thread_posix.cc
blob0d821a9b7ad803099817e16be62a6014a79f9e04
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::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();
83 return NULL;
86 bool CreateThread(size_t stack_size, bool joinable,
87 PlatformThread::Delegate* delegate,
88 PlatformThreadHandle* thread_handle,
89 ThreadPriority priority) {
90 base::InitThreading();
92 bool success = false;
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.
98 if (!joinable) {
99 pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
102 // Get a better default if available.
103 if (stack_size == 0)
104 stack_size = base::GetDefaultThreadStackSize(attributes);
106 if (stack_size > 0)
107 pthread_attr_setstacksize(&attributes, stack_size);
109 ThreadParams params;
110 params.delegate = delegate;
111 params.joinable = joinable;
112 params.priority = priority;
113 params.handle = thread_handle;
115 pthread_t handle;
116 int err = pthread_create(&handle,
117 &attributes,
118 ThreadFunc,
119 &params);
120 success = !err;
121 if (!success) {
122 // Value of |handle| is undefined if pthread_create fails.
123 handle = 0;
124 errno = err;
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.
132 if (success)
133 params.handle_set.Wait();
134 CHECK_EQ(handle, thread_handle->platform_handle());
136 return success;
139 } // namespace
141 // static
142 PlatformThreadId PlatformThread::CurrentId() {
143 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
144 // into the kernel.
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)
150 return gettid();
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());
160 #endif
163 // static
164 PlatformThreadRef PlatformThread::CurrentRef() {
165 return PlatformThreadRef(pthread_self());
168 // static
169 PlatformThreadHandle PlatformThread::CurrentHandle() {
170 return PlatformThreadHandle(pthread_self(), CurrentId());
173 // static
174 void PlatformThread::YieldCurrentThread() {
175 sched_yield();
178 // static
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;
193 // static
194 const char* PlatformThread::GetName() {
195 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
198 // static
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);
206 // static
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);
215 // static
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);
222 return result;
225 // static
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 /
229 // blocking tasks.
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)
237 // static
238 void PlatformThread::SetThreadPriority(PlatformThreadHandle handle,
239 ThreadPriority priority) {
240 #if defined(OS_NACL)
241 NOTIMPLEMENTED();
242 #else
243 if (internal::SetThreadPriorityForPlatform(handle, priority))
244 return;
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(),
256 nice_setting)) {
257 DVPLOG(1) << "Failed to set nice value of thread (" << handle.id()
258 << ") to " << nice_setting;
260 #endif // defined(OS_NACL)
263 // static
264 ThreadPriority PlatformThread::GetThreadPriority(PlatformThreadHandle handle) {
265 #if defined(OS_NACL)
266 NOTIMPLEMENTED();
267 return ThreadPriority::NORMAL;
268 #else
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
280 errno = 0;
281 int nice_value =
282 getpriority(PRIO_PROCESS, handle.id() == current_id ? 0 : handle.id());
283 if (errno != 0) {
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)
294 } // namespace base