From ad566646cf02163373c5d60033be07c2d903ef90 Mon Sep 17 00:00:00 2001 From: Kornel Date: Mon, 17 Feb 2025 17:22:01 +0000 Subject: Use faster thread_local in current_thread_id() --- library/std/src/sync/mpmc/mod.rs | 3 +++ library/std/src/sync/mpmc/tests.rs | 14 ++++++++++++++ library/std/src/sync/mpmc/waker.rs | 2 +- 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 library/std/src/sync/mpmc/tests.rs (limited to 'library/std/src/sync') diff --git a/library/std/src/sync/mpmc/mod.rs b/library/std/src/sync/mpmc/mod.rs index 8caa2dcfad9..8712332dd27 100644 --- a/library/std/src/sync/mpmc/mod.rs +++ b/library/std/src/sync/mpmc/mod.rs @@ -1382,3 +1382,6 @@ impl fmt::Debug for Receiver { f.pad("Receiver { .. }") } } + +#[cfg(test)] +mod tests; diff --git a/library/std/src/sync/mpmc/tests.rs b/library/std/src/sync/mpmc/tests.rs new file mode 100644 index 00000000000..6deb4dc2fe0 --- /dev/null +++ b/library/std/src/sync/mpmc/tests.rs @@ -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()); +} diff --git a/library/std/src/sync/mpmc/waker.rs b/library/std/src/sync/mpmc/waker.rs index 1895466f95d..f5e764e69bd 100644 --- a/library/std/src/sync/mpmc/waker.rs +++ b/library/std/src/sync/mpmc/waker.rs @@ -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()) } -- cgit 1.4.1-3-g733a5