pub fn get_id() -> u64 {
_get_native_thread_id()
}
mod inner {
#[cfg(target_os = "haiku")]
use std::os::raw::c_char;
#[cfg(target_os = "linux")]
unsafe extern "C" {
pub fn gettid() -> i32;
}
#[cfg(target_os = "openbsd")]
unsafe extern "C" {
pub fn getthrid() -> i32;
}
#[cfg(target_os = "freebsd")]
unsafe extern "C" {
pub fn pthread_getthreadid_np() -> i32;
}
#[cfg(target_os = "netbsd")]
unsafe extern "C" {
pub fn _lwp_self() -> i32;
}
#[cfg(any(target_os = "illumos", target_os = "solaris"))]
unsafe extern "C" {
pub fn thr_self() -> u32;
}
#[cfg(target_os = "haiku")]
unsafe extern "C" {
pub fn find_thread(name: *const c_char) -> i32;
}
#[cfg(target_os = "macos")]
unsafe extern "C" {
pub fn pthread_threadid_np(thread: *const c_void, thread_id: *mut u64);
}
}
#[cfg(target_os = "linux")]
fn _get_native_thread_id() -> u64 {
unsafe { inner::gettid() as u64 }
}
#[cfg(target_os = "openbsd")]
fn _get_native_thread_id() -> u64 {
unsafe { inner::getthrid() as u64 }
}
#[cfg(target_os = "freebsd")]
fn _get_native_thread_id() -> u64 {
unsafe { inner::pthread_getthreadid_np() as u64 }
}
#[cfg(target_os = "netbsd")]
fn _get_native_thread_id() -> u64 {
unsafe { inner::_lwp_self() as u64 }
}
#[cfg(any(target_os = "illumos", target_os = "solaris"))]
fn _get_native_thread_id() -> u64 {
unsafe { inner::thr_self() as u64 }
}
#[cfg(target_os = "haiku")]
fn _get_native_thread_id() -> u64 {
unsafe { inner::find_thread(std::ptr::null()) as u64 }
}
#[cfg(target_os = "macos")]
fn _get_native_thread_id() -> u64 {
unsafe {
let mut tid: u64 = 0;
inner::pthread_threadid_np(std::ptr::null(), &mut tid);
tid
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
#[test]
fn test_get_native_thread_id() {
let main_tid = get_id();
assert_ne!(main_tid, 0);
let t = thread::spawn(move || {
let tid = get_id();
assert_ne!(tid, 0);
assert_ne!(tid, main_tid);
});
t.join().unwrap();
}
}