platform_thread_posix.cc revision d0247b1b59f9c528cb6df88b4f2b9afaf80d181e
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.
4
5#include "base/threading/platform_thread.h"
6
7#include <errno.h>
8#include <sched.h>
9
10#include "base/lazy_instance.h"
11#include "base/logging.h"
12#include "base/memory/scoped_ptr.h"
13#include "base/safe_strerror_posix.h"
14#include "base/synchronization/waitable_event.h"
15#include "base/threading/thread_id_name_manager.h"
16#include "base/threading/thread_restrictions.h"
17#include "base/tracked_objects.h"
18
19#if defined(OS_MACOSX)
20#include <sys/resource.h>
21#include <algorithm>
22#endif
23
24#if defined(OS_LINUX)
25#include <sys/prctl.h>
26#include <sys/resource.h>
27#include <sys/syscall.h>
28#include <sys/time.h>
29#include <unistd.h>
30#endif
31
32namespace base {
33
34void InitThreading();
35void InitOnThread();
36void TerminateOnThread();
37size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
38
39namespace {
40
41struct ThreadParams {
42  ThreadParams()
43      : delegate(NULL),
44        joinable(false),
45        priority(kThreadPriority_Normal),
46        handle(NULL),
47        handle_set(false, false) {
48  }
49
50  PlatformThread::Delegate* delegate;
51  bool joinable;
52  ThreadPriority priority;
53  PlatformThreadHandle* handle;
54  WaitableEvent handle_set;
55};
56
57void* ThreadFunc(void* params) {
58  base::InitOnThread();
59  ThreadParams* thread_params = static_cast<ThreadParams*>(params);
60
61  PlatformThread::Delegate* delegate = thread_params->delegate;
62  if (!thread_params->joinable)
63    base::ThreadRestrictions::SetSingletonAllowed(false);
64
65  if (thread_params->priority != kThreadPriority_Normal) {
66    PlatformThread::SetThreadPriority(PlatformThread::CurrentHandle(),
67                                      thread_params->priority);
68  }
69
70  // Stash the id in the handle so the calling thread has a complete
71  // handle, and unblock the parent thread.
72  *(thread_params->handle) = PlatformThreadHandle(pthread_self(),
73                                                  PlatformThread::CurrentId());
74  thread_params->handle_set.Signal();
75
76  ThreadIdNameManager::GetInstance()->RegisterThread(
77      PlatformThread::CurrentHandle().platform_handle(),
78      PlatformThread::CurrentId());
79
80  delegate->ThreadMain();
81
82  ThreadIdNameManager::GetInstance()->RemoveName(
83      PlatformThread::CurrentHandle().platform_handle(),
84      PlatformThread::CurrentId());
85
86  base::TerminateOnThread();
87  return NULL;
88}
89
90bool CreateThread(size_t stack_size, bool joinable,
91                  PlatformThread::Delegate* delegate,
92                  PlatformThreadHandle* thread_handle,
93                  ThreadPriority priority) {
94  base::InitThreading();
95
96  bool success = false;
97  pthread_attr_t attributes;
98  pthread_attr_init(&attributes);
99
100  // Pthreads are joinable by default, so only specify the detached
101  // attribute if the thread should be non-joinable.
102  if (!joinable) {
103    pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
104  }
105
106  // Get a better default if available.
107  if (stack_size == 0)
108    stack_size = base::GetDefaultThreadStackSize(attributes);
109
110  if (stack_size > 0)
111    pthread_attr_setstacksize(&attributes, stack_size);
112
113  ThreadParams params;
114  params.delegate = delegate;
115  params.joinable = joinable;
116  params.priority = priority;
117  params.handle = thread_handle;
118
119  pthread_t handle = 0;
120  int err = pthread_create(&handle,
121                           &attributes,
122                           ThreadFunc,
123                           &params);
124  success = !err;
125  if (!success) {
126    errno = err;
127    PLOG(ERROR) << "pthread_create";
128  }
129
130  pthread_attr_destroy(&attributes);
131
132  // Don't let this call complete until the thread id
133  // is set in the handle.
134  if (success)
135    params.handle_set.Wait();
136  CHECK_EQ(handle, thread_handle->platform_handle());
137
138  return success;
139}
140
141}  // namespace
142
143// static
144PlatformThreadId PlatformThread::CurrentId() {
145  // Pthreads doesn't have the concept of a thread ID, so we have to reach down
146  // into the kernel.
147#if defined(OS_MACOSX)
148  return pthread_mach_thread_np(pthread_self());
149#elif defined(OS_LINUX)
150  return syscall(__NR_gettid);
151#elif defined(OS_ANDROID)
152  return gettid();
153#elif defined(OS_SOLARIS)
154  return pthread_self();
155#elif defined(OS_NACL) && defined(__GLIBC__)
156  return pthread_self();
157#elif defined(OS_NACL) && !defined(__GLIBC__)
158  // Pointers are 32-bits in NaCl.
159  return reinterpret_cast<int32>(pthread_self());
160#elif defined(OS_POSIX)
161  return reinterpret_cast<int64>(pthread_self());
162#endif
163}
164
165//static
166PlatformThreadHandle PlatformThread::CurrentHandle() {
167  return PlatformThreadHandle(pthread_self(), CurrentId());
168}
169
170// static
171void PlatformThread::YieldCurrentThread() {
172  sched_yield();
173}
174
175// static
176void PlatformThread::Sleep(TimeDelta duration) {
177  struct timespec sleep_time, remaining;
178
179  // Break the duration into seconds and nanoseconds.
180  // NOTE: TimeDelta's microseconds are int64s while timespec's
181  // nanoseconds are longs, so this unpacking must prevent overflow.
182  sleep_time.tv_sec = duration.InSeconds();
183  duration -= TimeDelta::FromSeconds(sleep_time.tv_sec);
184  sleep_time.tv_nsec = duration.InMicroseconds() * 1000;  // nanoseconds
185
186  while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
187    sleep_time = remaining;
188}
189
190// static
191const char* PlatformThread::GetName() {
192  return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
193}
194
195// static
196bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
197                            PlatformThreadHandle* thread_handle) {
198  base::ThreadRestrictions::ScopedAllowWait allow_wait;
199  return CreateThread(stack_size, true /* joinable thread */,
200                      delegate, thread_handle, kThreadPriority_Normal);
201}
202
203// static
204bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
205                                        PlatformThreadHandle* thread_handle,
206                                        ThreadPriority priority) {
207  base::ThreadRestrictions::ScopedAllowWait allow_wait;
208  return CreateThread(stack_size, true,  // joinable thread
209                      delegate, thread_handle, priority);
210}
211
212// static
213bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
214  PlatformThreadHandle unused;
215
216  base::ThreadRestrictions::ScopedAllowWait allow_wait;
217  bool result = CreateThread(stack_size, false /* non-joinable thread */,
218                             delegate, &unused, kThreadPriority_Normal);
219  return result;
220}
221
222// static
223void PlatformThread::Join(PlatformThreadHandle thread_handle) {
224  // Joining another thread may block the current thread for a long time, since
225  // the thread referred to by |thread_handle| may still be running long-lived /
226  // blocking tasks.
227  base::ThreadRestrictions::AssertIOAllowed();
228  CHECK_EQ(0, pthread_join(thread_handle.handle_, NULL));
229}
230
231}  // namespace base
232