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#![doc = include_str!("../README.md")]
15
16/// Get the current thread's thread id.
17///
18/// ```
19/// use gettid::gettid;
20/// let main_tid = gettid();
21/// let pid = std::process::id();
22///
23/// if cfg!(target_os = "linux") {
24/// // On Linux, the first thread ID is the same as the PID
25/// assert_eq!(pid as u64, main_tid);
26/// }
27///
28/// // gettid() returns a consistent value for a given thread.
29/// assert_eq!(main_tid, gettid());
30///
31/// let thread_tid = std::thread::spawn(gettid).join().unwrap();
32/// assert_ne!(main_tid, thread_tid);
33/// ```
34pub fn gettid() -> u64 {
35 gettid_impl()
36}
37
38#[cfg(any(target_os = "linux", target_os = "android"))]
39pub fn gettid_impl() -> u64 {
40 unsafe { libc::gettid() as u64 }
41}
42
43#[cfg(target_os = "macos")]
44pub fn gettid_impl() -> u64 {
45 let mut result = 0;
46 let res = unsafe { libc::pthread_threadid_np(0, &mut result) };
47 assert_eq!(res, 0, "error retrieving thread ID");
48 result
49}
50
51#[cfg(target_os = "freebsd")]
52pub fn gettid_impl() -> u64 {
53 unsafe { libc::pthread_getthreadid_np() as u64 }
54}
55
56#[cfg(target_os = "openbsd")]
57pub fn gettid_impl() -> u64 {
58 unsafe { libc::getthrid() as u64 }
59}
60
61#[cfg(target_os = "netbsd")]
62pub fn gettid_impl() -> u64 {
63 unsafe { libc::_lwp_self() as u64 }
64}
65
66#[cfg(target_os = "windows")]
67pub fn gettid_impl() -> u64 {
68 unsafe extern "system" {
69 fn GetCurrentThreadId() -> u32;
70 }
71
72 unsafe { GetCurrentThreadId().into() }
73}