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 if unsafe { libc::pthread_key_create(&mut key, mem::transmute(dtor)) } != 0 {
29 rtabort!("out of TLS keys");
30 }
31 key
32}
33
34#[inline]
35pub unsafe fn set(key: Key, value: *mut u8) {
36 let r = unsafe { libc::pthread_setspecific(key, value as *mut _) };
37 debug_assert_eq!(r, 0);
38}
39
40#[inline]
41#[cfg(any(not(target_thread_local), test))]
42pub unsafe fn get(key: Key) -> *mut u8 {
43 unsafe { libc::pthread_getspecific(key) as *mut u8 }
44}
45
46#[inline]
47pub unsafe fn destroy(key: Key) {
48 let r = unsafe { libc::pthread_key_delete(key) };
49 debug_assert_eq!(r, 0);
50}