Skip to content

Commit afaeae3

Browse files
committed
Refactor thread_info to remove the RefCell
`thread_info` currently uses `RefCell`-based initialization. Refactor this to use `OnceCell` instead which is more performant and better suits the needs of one-time initialization.
1 parent 5d62ab8 commit afaeae3

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed
Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,48 @@
11
#![allow(dead_code)] // stack_guard isn't used right now on all platforms
22

3-
use crate::cell::RefCell;
3+
use crate::cell::OnceCell;
44
use crate::sys::thread::guard::Guard;
55
use crate::thread::Thread;
66

7+
// 32, 0x8
78
struct ThreadInfo {
8-
stack_guard: Option<Guard>,
9-
thread: Thread,
9+
stack_guard: OnceCell<Guard>,
10+
thread: OnceCell<Thread>,
1011
}
1112

12-
thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = const { RefCell::new(None) } }
13+
thread_local! {
14+
static THREAD_INFO: ThreadInfo = const { ThreadInfo {
15+
stack_guard: OnceCell::new(),
16+
thread: OnceCell::new()
17+
} };
18+
}
1319

1420
impl ThreadInfo {
1521
fn with<R, F>(f: F) -> Option<R>
1622
where
17-
F: FnOnce(&mut ThreadInfo) -> R,
23+
F: FnOnce(&Thread, &OnceCell<Guard>) -> R,
1824
{
1925
THREAD_INFO
2026
.try_with(move |thread_info| {
21-
let mut thread_info = thread_info.borrow_mut();
22-
let thread_info = thread_info.get_or_insert_with(|| ThreadInfo {
23-
stack_guard: None,
24-
thread: Thread::new(None),
25-
});
26-
f(thread_info)
27+
let thread = thread_info.thread.get_or_init(|| Thread::new(None));
28+
f(thread, &thread_info.stack_guard)
2729
})
2830
.ok()
2931
}
3032
}
3133

3234
pub fn current_thread() -> Option<Thread> {
33-
ThreadInfo::with(|info| info.thread.clone())
35+
ThreadInfo::with(|thread, _| thread.clone())
3436
}
3537

3638
pub fn stack_guard() -> Option<Guard> {
37-
ThreadInfo::with(|info| info.stack_guard.clone()).and_then(|o| o)
39+
ThreadInfo::with(|_, guard| guard.get().cloned()).flatten()
3840
}
3941

4042
pub fn set(stack_guard: Option<Guard>, thread: Thread) {
4143
THREAD_INFO.with(move |thread_info| {
42-
let mut thread_info = thread_info.borrow_mut();
43-
rtassert!(thread_info.is_none());
44-
*thread_info = Some(ThreadInfo { stack_guard, thread });
44+
rtassert!(thread_info.stack_guard.get().is_none() && thread_info.thread.get().is_none());
45+
stack_guard.map(|g| thread_info.stack_guard.set(g).unwrap());
46+
thread_info.thread.set(thread).unwrap();
4547
});
4648
}

0 commit comments

Comments
 (0)