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"
10 #if defined(OS_MACOSX)
11 #include <mach/mach.h>
12 #elif defined(OS_LINUX)
13 #include <sys/syscall.h>
17 #if defined(OS_MACOSX)
23 static void* ThreadFunc(void* closure
) {
24 PlatformThread::Delegate
* delegate
=
25 static_cast<PlatformThread::Delegate
*>(closure
);
26 delegate
->ThreadMain();
31 int PlatformThread::CurrentId() {
32 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
34 #if defined(OS_MACOSX)
35 return mach_thread_self();
36 #elif defined(OS_LINUX)
37 return syscall(__NR_gettid
);
42 void PlatformThread::YieldCurrentThread() {
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
;
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.
72 bool PlatformThread::Create(size_t stack_size
, Delegate
* delegate
,
73 PlatformThreadHandle
* thread_handle
) {
74 #if defined(OS_MACOSX)
75 base::InitThreading();
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.
86 pthread_attr_setstacksize(&attributes
, stack_size
);
88 success
= !pthread_create(thread_handle
, &attributes
, ThreadFunc
, delegate
);
90 pthread_attr_destroy(&attributes
);
95 void PlatformThread::Join(PlatformThreadHandle thread_handle
) {
96 pthread_join(thread_handle
, NULL
);