Skip to content

Commit 897b4a8

Browse files
committed
Only write to CURRENT_ID once.
This also adds a some comments explaining the interactions between `CURRENT_ID` and `CURRENT`.
1 parent 287218c commit 897b4a8

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

library/std/src/thread/mod.rs

+13-3
Original file line numberDiff line numberDiff line change
@@ -698,6 +698,9 @@ where
698698
}
699699

700700
thread_local! {
701+
// Invariant: `CURRENT` and `CURRENT_ID` will always be initialized
702+
// together. However, while `CURRENT_ID` will be available during
703+
// TLS constructors, `CURRENT` will not.
701704
static CURRENT: OnceCell<Thread> = const { OnceCell::new() };
702705
static CURRENT_ID: Cell<Option<ThreadId>> = const { Cell::new(None) };
703706
}
@@ -722,9 +725,13 @@ pub(crate) fn set_current(thread: Thread) {
722725
pub(crate) fn try_current() -> Option<Thread> {
723726
CURRENT
724727
.try_with(|current| {
725-
let thread = current.get_or_init(Thread::new_unnamed).clone();
726-
CURRENT_ID.set(Some(thread.id()));
727-
thread
728+
current
729+
.get_or_init(|| {
730+
let thread = Thread::new_unnamed();
731+
CURRENT_ID.set(Some(thread.id()));
732+
thread
733+
})
734+
.clone()
728735
})
729736
.ok()
730737
}
@@ -736,6 +743,9 @@ pub(crate) fn try_current() -> Option<Thread> {
736743
#[inline]
737744
pub(crate) fn try_current_id() -> Option<ThreadId> {
738745
if CURRENT_ID.get().is_none() {
746+
// If `CURRENT_ID` isn't initialized yet, then `CURRENT` must also not be initialized.
747+
// `try_current()` will try to initialize both `CURRENT` and `CURRENT_ID`.
748+
// Subsequent calls to `try_current_id` will then no longer enter this if-branch.
739749
let _ = try_current();
740750
}
741751
CURRENT_ID.get()

0 commit comments

Comments
 (0)