]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys_common/thread_info.rs
Make current_thread_unique_ptr work during thread destruction.
[rust.git] / library / std / src / sys_common / thread_info.rs
1 #![allow(dead_code)] // stack_guard isn't used right now on all platforms
2 #![allow(unused_unsafe)] // thread_local with `const {}` triggers this liny
3
4 use crate::cell::RefCell;
5 use crate::sys::thread::guard::Guard;
6 use crate::thread::Thread;
7
8 struct ThreadInfo {
9     stack_guard: Option<Guard>,
10     thread: Thread,
11 }
12
13 thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = const { RefCell::new(None) } }
14
15 impl ThreadInfo {
16     fn with<R, F>(f: F) -> Option<R>
17     where
18         F: FnOnce(&mut ThreadInfo) -> R,
19     {
20         THREAD_INFO
21             .try_with(move |thread_info| {
22                 let mut thread_info = thread_info.borrow_mut();
23                 let thread_info = thread_info.get_or_insert_with(|| ThreadInfo {
24                     stack_guard: None,
25                     thread: Thread::new(None),
26                 });
27                 f(thread_info)
28             })
29             .ok()
30     }
31 }
32
33 /// Get an address that is unique per running thread.
34 ///
35 /// This can be used as a non-null usize-sized ID.
36 pub fn current_thread_unique_ptr() -> usize {
37     // Use a non-drop type to make sure it's still available during thread destruction.
38     thread_local! { static X: u8 = 0 }
39     X.with(|x| <*const _>::addr(x))
40 }
41
42 pub fn current_thread() -> Option<Thread> {
43     ThreadInfo::with(|info| info.thread.clone())
44 }
45
46 pub fn stack_guard() -> Option<Guard> {
47     ThreadInfo::with(|info| info.stack_guard.clone()).and_then(|o| o)
48 }
49
50 pub fn set(stack_guard: Option<Guard>, thread: Thread) {
51     THREAD_INFO.with(move |thread_info| {
52         let mut thread_info = thread_info.borrow_mut();
53         rtassert!(thread_info.is_none());
54         *thread_info = Some(ThreadInfo { stack_guard, thread });
55     });
56 }