From a22426916ddf2f0b7927f31b7b7a8358f3e4827d Mon Sep 17 00:00:00 2001 From: Ibraheem Ahmed Date: Sat, 12 Nov 2022 23:13:58 -0500 Subject: [PATCH] avoid calling `thread::current` in channel destructor --- library/std/src/sync/mpmc/context.rs | 9 +++++---- library/std/src/sync/mpmc/waker.rs | 15 ++++++--------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/library/std/src/sync/mpmc/context.rs b/library/std/src/sync/mpmc/context.rs index 3077c0ee375..bbfc6ce00ff 100644 --- a/library/std/src/sync/mpmc/context.rs +++ b/library/std/src/sync/mpmc/context.rs @@ -1,12 +1,13 @@ //! Thread-local channel context. use super::select::Selected; +use super::waker::current_thread_id; use crate::cell::Cell; use crate::ptr; use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use crate::sync::Arc; -use crate::thread::{self, Thread, ThreadId}; +use crate::thread::{self, Thread}; use crate::time::Instant; /// Thread-local context. @@ -28,7 +29,7 @@ struct Inner { thread: Thread, /// Thread id. - thread_id: ThreadId, + thread_id: usize, } impl Context { @@ -70,7 +71,7 @@ impl Context { select: AtomicUsize::new(Selected::Waiting.into()), packet: AtomicPtr::new(ptr::null_mut()), thread: thread::current(), - thread_id: thread::current().id(), + thread_id: current_thread_id(), }), } } @@ -148,7 +149,7 @@ impl Context { /// Returns the id of the thread this context belongs to. #[inline] - pub fn thread_id(&self) -> ThreadId { + pub fn thread_id(&self) -> usize { self.inner.thread_id } } diff --git a/library/std/src/sync/mpmc/waker.rs b/library/std/src/sync/mpmc/waker.rs index 572ac01d3f7..4912ca4f815 100644 --- a/library/std/src/sync/mpmc/waker.rs +++ b/library/std/src/sync/mpmc/waker.rs @@ -6,7 +6,6 @@ use super::select::{Operation, Selected}; use crate::ptr; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sync::Mutex; -use crate::thread::{self, ThreadId}; /// Represents a thread blocked on a specific channel operation. pub(crate) struct Entry { @@ -195,13 +194,11 @@ impl Drop for SyncWaker { } } -/// Returns the id of the current thread. +/// Returns a unique id for the current thread. #[inline] -fn current_thread_id() -> ThreadId { - thread_local! { - /// Cached thread-local id. - static THREAD_ID: ThreadId = thread::current().id(); - } - - THREAD_ID.try_with(|id| *id).unwrap_or_else(|_| thread::current().id()) +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 } + DUMMY.with(|x| (x as *const u8).addr()) }