gettid/lib.rs
1// Copyright (C) 2019 by Josh Gao <josh@jmgao.dev>
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted.
5//
6// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
7// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
8// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
9// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
10// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
11// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
12// PERFORMANCE OF THIS SOFTWARE.
13
14//! A crate to help with fetching thread ids across multiple platforms.
15
16#[cfg(any(target_os = "linux", target_os = "android", rustdoc))]
17mod imp {
18 /// Get the current thread's thread id.
19 ///
20 /// ```
21 /// use gettid::gettid;
22 /// let main_tid = gettid();
23 /// let pid = std::process::id();
24 /// assert_eq!(pid as u64, main_tid);
25 /// let thread_tid = std::thread::spawn(gettid).join().unwrap();
26 /// assert_ne!(main_tid, thread_tid);
27 /// ```
28 pub fn gettid() -> u64 {
29 unsafe { libc::syscall(libc::SYS_gettid) as u64 }
30 }
31}
32
33#[cfg(target_os = "macos")]
34mod imp {
35 #[link(name = "pthread")]
36 extern "C" {
37 fn pthread_threadid_np(thread: libc::pthread_t, thread_id: *mut u64) -> libc::c_int;
38 }
39
40 pub fn gettid() -> u64 {
41 let mut result = 0;
42 unsafe {let _ = pthread_threadid_np(0, &mut result); }
43 result
44 }
45}
46
47#[cfg(target_os = "freebsd")]
48mod imp {
49 #[link(name = "pthread")]
50 extern "C" {
51 fn pthread_getthreadid_np(thread: libc::pthread_t, thread_id: *mut u64) -> libc::c_int;
52 }
53
54 pub fn gettid() -> u64 {
55 let mut result = 0;
56 unsafe {let _ = pthread_getthreadid_np(0, &mut result); }
57 result
58 }
59}
60
61#[cfg(target_os = "windows")]
62mod imp {
63 pub fn gettid() -> u64 {
64 unsafe { winapi::um::processthreadsapi::GetCurrentThreadId().into() }
65 }
66}
67
68pub use imp::*;