1use crate::ThreadName;
2
3#[cfg(all(unix, not(target_os = "linux"), not(target_os = "android"), not(target_os = "macos"), not(target_os = "ios"), not(target_os = "netbsd"), not(target_os = "freebsd")))]
4pub type RawId = libc::pthread_t;
6
7#[cfg(any(target_os = "linux", target_os = "android"))]
8pub type RawId = libc::pid_t;
12
13#[cfg(target_os = "freebsd")]
14pub type RawId = libc::c_int;
18
19#[cfg(target_os = "netbsd")]
20pub type RawId = libc::c_uint;
24
25#[cfg(any(target_os = "macos", target_os = "ios"))]
26pub type RawId = u64;
30
31#[cfg(target_os = "freebsd")]
32#[inline]
33pub fn get_raw_id() -> RawId {
35 #[link(name = "pthread")]
36 extern "C" {
37 fn pthread_getthreadid_np() -> libc::c_int;
38 }
39
40 unsafe { pthread_getthreadid_np() }
42}
43
44#[cfg(target_os = "netbsd")]
45#[inline]
46pub fn get_raw_id() -> RawId {
48 extern "C" {
49 fn _lwp_self() -> libc::c_uint;
50 }
51
52 unsafe { _lwp_self() }
54}
55
56#[cfg(any(target_os = "macos", target_os = "ios"))]
57#[inline]
58pub fn get_raw_id() -> RawId {
60 #[link(name = "pthread")]
61 extern "C" {
62 fn pthread_threadid_np(thread: libc::pthread_t, thread_id: *mut u64) -> libc::c_int;
63 }
64 let mut tid: u64 = 0;
65 let err = unsafe { pthread_threadid_np(0, &mut tid) };
66 assert_eq!(err, 0);
67 tid
68}
69
70#[cfg(any(target_os = "android", target_os = "linux"))]
71#[inline]
72pub fn get_raw_id() -> RawId {
74 unsafe { libc::syscall(libc::SYS_gettid) as libc::pid_t }
75}
76
77#[cfg(all(unix, not(target_os = "linux"), not(target_os = "android"), not(target_os = "macos"), not(target_os = "ios"), not(target_os = "netbsd"), not(target_os = "freebsd")))]
78#[inline]
79pub fn get_raw_id() -> RawId {
81 unsafe {
82 libc::pthread_self()
83 }
84}
85
86#[inline(always)]
87pub fn raw_thread_eq(left: RawId, right: RawId) -> bool {
91 #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos", target_os = "ios", target_os = "netbsd", target_os = "freebsd"))]
92 {
93 left == right
94 }
95
96 #[cfg(all(not(target_os = "linux"), not(target_os = "android"), not(target_os = "macos"), not(target_os = "ios"), not(target_os = "netbsd"), not(target_os = "freebsd")))]
97 {
98 #[link(name = "pthread")]
99 extern "C" {
100 pub fn pthread_equal(left: RawId, right: RawId) -> libc::c_int;
101 }
102
103 unsafe {
104 pthread_equal(left, right) != 0
105 }
106 }
107}
108
109pub fn get_current_thread_name() -> ThreadName {
111 #[link(name = "pthread")]
112 extern "C" {
113 pub fn pthread_getname_np(thread: libc::pthread_t, name: *mut i8, len: libc::size_t) -> libc::c_int;
114 }
115
116 let mut storage = [0u8; 16];
117
118 let result = unsafe {
119 pthread_getname_np(libc::pthread_self(), storage.as_mut_ptr() as _, storage.len() as _)
120 };
121
122 if result == 0 {
123 ThreadName::name(storage)
124 } else {
125 ThreadName::new()
126 }
127}