1 // Copyright (c) 2011 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"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/safe_strerror_posix.h"
13 #include "base/threading/thread_local.h"
14 #include "base/threading/thread_restrictions.h"
16 #if defined(OS_MACOSX)
17 #include <mach/mach.h>
18 #include <sys/resource.h>
24 #include <sys/prctl.h>
25 #include <sys/syscall.h>
29 #if defined(OS_ANDROID)
30 #include "base/android/jni_android.h"
34 #include <sys/nacl_syscalls.h>
39 #if defined(OS_MACOSX)
45 static ThreadLocalPointer<char> current_thread_name;
48 PlatformThread::Delegate* delegate;
52 void* ThreadFunc(void* params) {
53 ThreadParams* thread_params = static_cast<ThreadParams*>(params);
54 PlatformThread::Delegate* delegate = thread_params->delegate;
55 if (!thread_params->joinable)
56 base::ThreadRestrictions::SetSingletonAllowed(false);
58 delegate->ThreadMain();
59 #if defined(OS_ANDROID)
60 base::android::DetachFromVM();
65 bool CreateThread(size_t stack_size, bool joinable,
66 PlatformThread::Delegate* delegate,
67 PlatformThreadHandle* thread_handle) {
68 #if defined(OS_MACOSX)
69 base::InitThreading();
73 pthread_attr_t attributes;
74 pthread_attr_init(&attributes);
76 // Pthreads are joinable by default, so only specify the detached attribute if
77 // the thread should be non-joinable.
79 pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
82 #if defined(OS_MACOSX)
83 // The Mac OS X default for a pthread stack size is 512kB.
84 // Libc-594.1.4/pthreads/pthread.c's pthread_attr_init uses
85 // DEFAULT_STACK_SIZE for this purpose.
87 // 512kB isn't quite generous enough for some deeply recursive threads that
88 // otherwise request the default stack size by specifying 0. Here, adopt
89 // glibc's behavior as on Linux, which is to use the current stack size
90 // limit (ulimit -s) as the default stack size. See
91 // glibc-2.11.1/nptl/nptl-init.c's __pthread_initialize_minimal_internal. To
92 // avoid setting the limit below the Mac OS X default or the minimum usable
93 // stack size, these values are also considered. If any of these values
94 // can't be determined, or if stack size is unlimited (ulimit -s unlimited),
95 // stack_size is left at 0 to get the system default.
97 // Mac OS X normally only applies ulimit -s to the main thread stack. On
98 // contemporary OS X and Linux systems alike, this value is generally 8MB
99 // or in that neighborhood.
100 if (stack_size == 0) {
101 size_t default_stack_size;
102 struct rlimit stack_rlimit;
103 if (pthread_attr_getstacksize(&attributes, &default_stack_size) == 0 &&
104 getrlimit(RLIMIT_STACK, &stack_rlimit) == 0 &&
105 stack_rlimit.rlim_cur != RLIM_INFINITY) {
106 stack_size = std::max(std::max(default_stack_size,
107 static_cast<size_t>(PTHREAD_STACK_MIN)),
108 static_cast<size_t>(stack_rlimit.rlim_cur));
114 pthread_attr_setstacksize(&attributes, stack_size);
116 ThreadParams* params = new ThreadParams;
117 params->delegate = delegate;
118 params->joinable = joinable;
119 success = !pthread_create(thread_handle, &attributes, ThreadFunc, params);
121 pthread_attr_destroy(&attributes);
130 PlatformThreadId PlatformThread::CurrentId() {
131 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
133 #if defined(OS_MACOSX)
134 return mach_thread_self();
135 #elif defined(OS_LINUX)
136 return syscall(__NR_gettid);
137 #elif defined(OS_ANDROID)
139 #elif defined(OS_FREEBSD)
140 // TODO(BSD): find a better thread ID
141 return reinterpret_cast<int64>(pthread_self());
142 #elif defined(OS_NACL) || defined(OS_SOLARIS)
143 return pthread_self();
148 void PlatformThread::YieldCurrentThread() {
153 void PlatformThread::Sleep(int duration_ms) {
154 struct timespec sleep_time, remaining;
156 // Contains the portion of duration_ms >= 1 sec.
157 sleep_time.tv_sec = duration_ms / 1000;
158 duration_ms -= sleep_time.tv_sec * 1000;
160 // Contains the portion of duration_ms < 1 sec.
161 sleep_time.tv_nsec = duration_ms * 1000 * 1000; // nanoseconds.
163 while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
164 sleep_time = remaining;
167 // Linux SetName is currently disabled, as we need to distinguish between
168 // helper threads (where it's ok to make this call) and the main thread
169 // (where making this call renames our process, causing tools like killall
171 #if 0 && defined(OS_LINUX)
173 void PlatformThread::SetName(const char* name) {
174 // have to cast away const because ThreadLocalPointer does not support const
176 current_thread_name.Set(const_cast<char*>(name));
178 // http://0pointer.de/blog/projects/name-your-threads.html
180 // glibc recently added support for pthread_setname_np, but it's not
181 // commonly available yet. So test for it at runtime.
182 int (*dynamic_pthread_setname_np)(pthread_t, const char*);
183 *reinterpret_cast<void**>(&dynamic_pthread_setname_np) =
184 dlsym(RTLD_DEFAULT, "pthread_setname_np");
186 if (dynamic_pthread_setname_np) {
187 // This limit comes from glibc, which gets it from the kernel
189 const int kMaxNameLength = 15;
190 std::string shortened_name = std::string(name).substr(0, kMaxNameLength);
191 int err = dynamic_pthread_setname_np(pthread_self(),
192 shortened_name.c_str());
194 LOG(ERROR) << "pthread_setname_np: " << safe_strerror(err);
196 // Implementing this function without glibc is simple enough. (We
197 // don't do the name length clipping as above because it will be
198 // truncated by the callee (see TASK_COMM_LEN above).)
199 int err = prctl(PR_SET_NAME, name);
201 PLOG(ERROR) << "prctl(PR_SET_NAME)";
204 #elif defined(OS_MACOSX)
205 // Mac is implemented in platform_thread_mac.mm.
208 void PlatformThread::SetName(const char* name) {
209 // have to cast away const because ThreadLocalPointer does not support const
211 current_thread_name.Set(const_cast<char*>(name));
213 // (This should be relatively simple to implement for the BSDs; I
214 // just don't have one handy to test the code on.)
216 #endif // defined(OS_LINUX)
219 #if !defined(OS_MACOSX)
220 // Mac is implemented in platform_thread_mac.mm.
222 const char* PlatformThread::GetName() {
223 return current_thread_name.Get();
228 bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
229 PlatformThreadHandle* thread_handle) {
230 return CreateThread(stack_size, true /* joinable thread */,
231 delegate, thread_handle);
235 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
236 PlatformThreadHandle unused;
238 bool result = CreateThread(stack_size, false /* non-joinable thread */,
244 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
245 // Joining another thread may block the current thread for a long time, since
246 // the thread referred to by |thread_handle| may still be running long-lived /
248 base::ThreadRestrictions::AssertIOAllowed();
249 pthread_join(thread_handle, NULL);
252 #if !defined(OS_MACOSX)
253 // Mac OS X uses lower-level mach APIs
256 void PlatformThread::SetThreadPriority(PlatformThreadHandle, ThreadPriority) {
257 // TODO(crogers): implement