"Make Chrome your default browser" should now appear as a checkbox at the bottom...
[chromium-blink-merge.git] / base / platform_thread_posix.cc
blob77f5bee2c297a1b00cc2f20a4f1b934657e24daa
1 // Copyright (c) 2006-2008 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/platform_thread.h"
7 #include <errno.h>
8 #include <sched.h>
10 #if defined(OS_MACOSX)
11 #include <mach/mach.h>
12 #elif defined(OS_LINUX)
13 #include <sys/syscall.h>
14 #include <unistd.h>
15 #endif
17 #if defined(OS_MACOSX)
18 namespace base {
19 void InitThreading();
20 } // namespace
21 #endif
23 static void* ThreadFunc(void* closure) {
24 PlatformThread::Delegate* delegate =
25 static_cast<PlatformThread::Delegate*>(closure);
26 delegate->ThreadMain();
27 return NULL;
30 // static
31 int PlatformThread::CurrentId() {
32 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
33 // into the kernel.
34 #if defined(OS_MACOSX)
35 return mach_thread_self();
36 #elif defined(OS_LINUX)
37 return syscall(__NR_gettid);
38 #endif
41 // static
42 void PlatformThread::YieldCurrentThread() {
43 sched_yield();
46 // static
47 void PlatformThread::Sleep(int duration_ms) {
48 struct timespec sleep_time, remaining;
50 // Contains the portion of duration_ms >= 1 sec.
51 sleep_time.tv_sec = duration_ms / 1000;
52 duration_ms -= sleep_time.tv_sec * 1000;
54 // Contains the portion of duration_ms < 1 sec.
55 sleep_time.tv_nsec = duration_ms * 1000 * 1000; // nanoseconds.
57 while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
58 sleep_time = remaining;
61 // static
62 void PlatformThread::SetName(const char* name) {
63 // The POSIX standard does not provide for naming threads, and neither Linux
64 // nor Mac OS X (our two POSIX targets) provide any non-portable way of doing
65 // it either. (Some BSDs provide pthread_set_name_np but that isn't much of a
66 // consolation prize.)
67 // TODO(darin): decide whether stuffing the name in TLS or other in-memory
68 // structure would be useful for debugging or not.
71 // static
72 bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
73 PlatformThreadHandle* thread_handle) {
74 #if defined(OS_MACOSX)
75 base::InitThreading();
76 #endif // OS_MACOSX
78 bool success = false;
79 pthread_attr_t attributes;
80 pthread_attr_init(&attributes);
82 // Pthreads are joinable by default, so we don't need to specify any special
83 // attributes to be able to call pthread_join later.
85 if (stack_size > 0)
86 pthread_attr_setstacksize(&attributes, stack_size);
88 success = !pthread_create(thread_handle, &attributes, ThreadFunc, delegate);
90 pthread_attr_destroy(&attributes);
91 return success;
94 // static
95 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
96 pthread_join(thread_handle, NULL);