std/sys/thread_local/key/
unix.rs
1use crate::mem;
2
3#[cfg(all(target_os = "wasi", target_env = "p1", target_feature = "atomics"))]
5mod libc {
6 use crate::ffi;
7
8 #[allow(non_camel_case_types)]
9 pub type pthread_key_t = ffi::c_uint;
10
11 unsafe extern "C" {
12 pub fn pthread_key_create(
13 key: *mut pthread_key_t,
14 destructor: unsafe extern "C" fn(*mut ffi::c_void),
15 ) -> ffi::c_int;
16 #[allow(dead_code)]
17 pub fn pthread_getspecific(key: pthread_key_t) -> *mut ffi::c_void;
18 pub fn pthread_setspecific(key: pthread_key_t, value: *const ffi::c_void) -> ffi::c_int;
19 pub fn pthread_key_delete(key: pthread_key_t) -> ffi::c_int;
20 }
21}
22
23pub type Key = libc::pthread_key_t;
24
25#[inline]
26pub fn create(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> Key {
27 let mut key = 0;
28 assert_eq!(unsafe { libc::pthread_key_create(&mut key, mem::transmute(dtor)) }, 0);
29 key
30}
31
32#[inline]
33pub unsafe fn set(key: Key, value: *mut u8) {
34 let r = unsafe { libc::pthread_setspecific(key, value as *mut _) };
35 debug_assert_eq!(r, 0);
36}
37
38#[inline]
39#[cfg(any(not(target_thread_local), test))]
40pub unsafe fn get(key: Key) -> *mut u8 {
41 unsafe { libc::pthread_getspecific(key) as *mut u8 }
42}
43
44#[inline]
45pub unsafe fn destroy(key: Key) {
46 let r = unsafe { libc::pthread_key_delete(key) };
47 debug_assert_eq!(r, 0);
48}