about summary refs log tree commit diff
diff options
context:
space:
mode:
authorKornel <kornel@geekhood.net>2025-02-17 17:22:01 +0000
committerKornel <kornel@geekhood.net>2025-02-21 13:09:16 +0000
commitad566646cf02163373c5d60033be07c2d903ef90 (patch)
tree7159fae1c9020776670fab012a41fe8cdcdc5b96
parentb94162078d43ee07277a8a746e4176588a7ab93b (diff)
downloadrust-ad566646cf02163373c5d60033be07c2d903ef90.tar.gz
rust-ad566646cf02163373c5d60033be07c2d903ef90.zip
Use faster thread_local in current_thread_id()
-rw-r--r--library/std/src/sync/mpmc/mod.rs3
-rw-r--r--library/std/src/sync/mpmc/tests.rs14
-rw-r--r--library/std/src/sync/mpmc/waker.rs2
3 files changed, 18 insertions, 1 deletions
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<T> fmt::Debug for Receiver<T> {
         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())
 }