Skip to content

Commit a224269

Browse files
committed
avoid calling thread::current in channel destructor
1 parent cd30f27 commit a224269

File tree

2 files changed

+11
-13
lines changed

2 files changed

+11
-13
lines changed

library/std/src/sync/mpmc/context.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
//! Thread-local channel context.
22
33
use super::select::Selected;
4+
use super::waker::current_thread_id;
45

56
use crate::cell::Cell;
67
use crate::ptr;
78
use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
89
use crate::sync::Arc;
9-
use crate::thread::{self, Thread, ThreadId};
10+
use crate::thread::{self, Thread};
1011
use crate::time::Instant;
1112

1213
/// Thread-local context.
@@ -28,7 +29,7 @@ struct Inner {
2829
thread: Thread,
2930

3031
/// Thread id.
31-
thread_id: ThreadId,
32+
thread_id: usize,
3233
}
3334

3435
impl Context {
@@ -70,7 +71,7 @@ impl Context {
7071
select: AtomicUsize::new(Selected::Waiting.into()),
7172
packet: AtomicPtr::new(ptr::null_mut()),
7273
thread: thread::current(),
73-
thread_id: thread::current().id(),
74+
thread_id: current_thread_id(),
7475
}),
7576
}
7677
}
@@ -148,7 +149,7 @@ impl Context {
148149

149150
/// Returns the id of the thread this context belongs to.
150151
#[inline]
151-
pub fn thread_id(&self) -> ThreadId {
152+
pub fn thread_id(&self) -> usize {
152153
self.inner.thread_id
153154
}
154155
}

library/std/src/sync/mpmc/waker.rs

+6-9
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ use super::select::{Operation, Selected};
66
use crate::ptr;
77
use crate::sync::atomic::{AtomicBool, Ordering};
88
use crate::sync::Mutex;
9-
use crate::thread::{self, ThreadId};
109

1110
/// Represents a thread blocked on a specific channel operation.
1211
pub(crate) struct Entry {
@@ -195,13 +194,11 @@ impl Drop for SyncWaker {
195194
}
196195
}
197196

198-
/// Returns the id of the current thread.
197+
/// Returns a unique id for the current thread.
199198
#[inline]
200-
fn current_thread_id() -> ThreadId {
201-
thread_local! {
202-
/// Cached thread-local id.
203-
static THREAD_ID: ThreadId = thread::current().id();
204-
}
205-
206-
THREAD_ID.try_with(|id| *id).unwrap_or_else(|_| thread::current().id())
199+
pub fn current_thread_id() -> usize {
200+
// `u8` is not drop so this variable will be available during thread destruction,
201+
// whereas `thread::current()` would not be
202+
thread_local! { static DUMMY: u8 = 0 }
203+
DUMMY.with(|x| (x as *const u8).addr())
207204
}

0 commit comments

Comments
 (0)