Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow spawning threads after TLS destruction #138702

Merged
merged 4 commits into from
Mar 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions library/std/src/thread/spawnhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,18 +113,23 @@ where
pub(super) fn run_spawn_hooks(thread: &Thread) -> ChildSpawnHooks {
// Get a snapshot of the spawn hooks.
// (Increments the refcount to the first node.)
let hooks = SPAWN_HOOKS.with(|hooks| {
if let Ok(hooks) = SPAWN_HOOKS.try_with(|hooks| {
let snapshot = hooks.take();
hooks.set(snapshot.clone());
snapshot
});
// Iterate over the hooks, run them, and collect the results in a vector.
let to_run: Vec<_> = iter::successors(hooks.first.as_deref(), |hook| hook.next.as_deref())
.map(|hook| (hook.hook)(thread))
.collect();
// Pass on the snapshot of the hooks and the results to the new thread,
// which will then run SpawnHookResults::run().
ChildSpawnHooks { hooks, to_run }
}) {
// Iterate over the hooks, run them, and collect the results in a vector.
let to_run: Vec<_> = iter::successors(hooks.first.as_deref(), |hook| hook.next.as_deref())
.map(|hook| (hook.hook)(thread))
.collect();
// Pass on the snapshot of the hooks and the results to the new thread,
// which will then run SpawnHookResults::run().
ChildSpawnHooks { hooks, to_run }
} else {
// TLS has been destroyed. Skip running the hooks.
// See https://github.com/rust-lang/rust/issues/138696
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we document this in add_spawn_hook ("for every newly thread spawned"), maybe as a footnote or something like that?

ChildSpawnHooks::default()
}
}

/// The results of running the spawn hooks.
Expand Down
24 changes: 24 additions & 0 deletions tests/ui/thread-local/spawn-hook-atexit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Regression test for https://github.com/rust-lang/rust/issues/138696
//@ only-unix
//@ needs-threads
//@ run-pass

#![feature(rustc_private)]

extern crate libc;

fn main() {
std::thread::spawn(|| {
unsafe { libc::atexit(spawn_in_atexit) };
})
.join()
.unwrap();
}

extern "C" fn spawn_in_atexit() {
std::thread::spawn(|| {
println!("Thread spawned in atexit");
})
.join()
.unwrap();
}
Loading