1
Fork 0

Use faster thread_local in current_thread_id()

This commit is contained in:
Kornel 2025-02-17 17:22:01 +00:00
parent b94162078d
commit ad566646cf
No known key found for this signature in database
3 changed files with 18 additions and 1 deletions

View file

@ -1382,3 +1382,6 @@ impl<T> fmt::Debug for Receiver<T> {
f.pad("Receiver { .. }")
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,14 @@
// Ensure that thread_local init with `const { 0 }` still has unique address at run-time
#[test]
fn waker_current_thread_id() {
let first = super::waker::current_thread_id();
let t = crate::thread::spawn(move || {
let second = super::waker::current_thread_id();
assert_ne!(first, second);
assert_eq!(second, super::waker::current_thread_id());
});
assert_eq!(first, super::waker::current_thread_id());
t.join().unwrap();
assert_eq!(first, super::waker::current_thread_id());
}

View file

@ -204,6 +204,6 @@ impl Drop for SyncWaker {
pub fn current_thread_id() -> usize {
// `u8` is not drop so this variable will be available during thread destruction,
// whereas `thread::current()` would not be
thread_local! { static DUMMY: u8 = 0 }
thread_local! { static DUMMY: u8 = const { 0 } }
DUMMY.with(|x| (x as *const u8).addr())
}