Skip to main content

std/thread/
spawnhook.rs

1use super::thread::Thread;
2use crate::cell::Cell;
3use crate::iter;
4use crate::sync::{Arc, UniqueArc};
5
6crate::thread_local! {
7    /// A thread local linked list of spawn hooks.
8    ///
9    /// It is a linked list of Arcs, such that it can very cheaply be inherited by spawned threads.
10    ///
11    /// (That technically makes it a set of linked lists with shared tails, so a linked tree.)
12    static SPAWN_HOOKS: Cell<SpawnHooks> = const { Cell::new(SpawnHooks { first: None }) };
13}
14
15#[ferrocene::prevalidated]
16#[derive(Default, Clone)]
17struct SpawnHooks {
18    first: Option<Arc<SpawnHook>>,
19}
20
21// Manually implement drop to prevent deep recursion when dropping linked Arc list.
22#[ferrocene::prevalidated]
23impl Drop for SpawnHooks {
24    fn drop(&mut self) {
25        let mut next = self.first.take();
26        // Ferrocene modification: Don't call `.and_then` but `match` to work around
27        // `ferrocene::unvalidated` bug.
28        // while let Some(SpawnHook { hook, next: n }) = next.and_then(Arc::into_inner) {
29        //     drop(hook);
30        //     next = n;
31        // }
32        while let Some(arc) = next {
33            match Arc::into_inner(arc) {
34                Some(SpawnHook { hook, next: n }) => {
35                    drop(hook);
36                    next = n;
37                }
38                None => break,
39            }
40        }
41    }
42}
43
44struct SpawnHook {
45    hook: Box<dyn Send + Sync + Fn(&Thread) -> Box<dyn Send + FnOnce()>>,
46    next: Option<Arc<SpawnHook>>,
47}
48
49/// Registers a function to run for every newly thread spawned.
50///
51/// The hook is executed in the parent thread, and returns a function
52/// that will be executed in the new thread.
53///
54/// The hook is called with the `Thread` handle for the new thread.
55///
56/// The hook will only be added for the current thread and is inherited by the threads it spawns.
57/// In other words, adding a hook has no effect on already running threads (other than the current
58/// thread) and the threads they might spawn in the future.
59///
60/// The hooks will run in reverse order, starting with the most recently added.
61///
62/// Hooks can only be added, not removed.
63/// Note that this does *not* mean that they are guaranteed to run. See [`Builder::no_hooks`].
64/// You cannot rely on a hook running for soundness.
65///
66/// # Usage
67///
68/// ```
69/// #![feature(thread_spawn_hook)]
70///
71/// std::thread::add_spawn_hook(|_| {
72///     ..; // This will run in the parent (spawning) thread.
73///     move || {
74///         ..; // This will run it the child (spawned) thread.
75///     }
76/// });
77/// ```
78///
79/// # Example
80///
81/// A spawn hook can be used to "inherit" a thread local from the parent thread:
82///
83/// ```
84/// #![feature(thread_spawn_hook)]
85///
86/// use std::cell::Cell;
87///
88/// thread_local! {
89///     static X: Cell<u32> = Cell::new(0);
90/// }
91///
92/// // This needs to be done once in the main thread before spawning any threads.
93/// std::thread::add_spawn_hook(|_| {
94///     // Get the value of X in the spawning thread.
95///     let value = X.get();
96///     // Set the value of X in the newly spawned thread.
97///     move || X.set(value)
98/// });
99///
100/// X.set(123);
101///
102/// std::thread::spawn(|| {
103///     assert_eq!(X.get(), 123);
104/// }).join().unwrap();
105/// ```
106///
107/// [`Builder::no_hooks`]: crate::thread::Builder::no_hooks
108#[unstable(feature = "thread_spawn_hook", issue = "132951")]
109pub fn add_spawn_hook<F, G>(hook: F)
110where
111    F: 'static + Send + Sync + Fn(&Thread) -> G,
112    G: 'static + Send + FnOnce(),
113{
114    SPAWN_HOOKS.with(|h| {
115        // Perform all fallible operations before taking the current hooks (see #159923)
116        let mut new_first = UniqueArc::new(SpawnHook {
117            hook: Box::new(move |thread| Box::new(hook(thread))),
118            next: None,
119        });
120        let mut hooks = h.take();
121        new_first.next = hooks.first.take();
122        hooks.first = Some(UniqueArc::into_arc(new_first));
123        h.set(hooks);
124    });
125}
126
127/// Runs all the spawn hooks.
128///
129/// Called on the parent thread.
130///
131/// Returns the functions to be called on the newly spawned thread.
132#[ferrocene::prevalidated]
133pub(super) fn run_spawn_hooks(thread: &Thread) -> ChildSpawnHooks {
134    // Get a snapshot of the spawn hooks.
135    // (Increments the refcount to the first node.)
136    if let Ok(hooks) = SPAWN_HOOKS.try_with(|hooks| {
137        let snapshot = hooks.take();
138        hooks.set(snapshot.clone());
139        snapshot
140    }) {
141        // Iterate over the hooks, run them, and collect the results in a vector.
142        #[allow(ferrocene::unvalidated, reason = "false-positive")]
143        let to_run: Vec<_> = iter::successors(hooks.first.as_deref(), |hook| hook.next.as_deref())
144            .map(|hook| (hook.hook)(thread))
145            .collect();
146        // Pass on the snapshot of the hooks and the results to the new thread,
147        // which will then run SpawnHookResults::run().
148        ChildSpawnHooks { hooks, to_run }
149    } else {
150        // TLS has been destroyed. Skip running the hooks.
151        // See https://github.com/rust-lang/rust/issues/138696
152        ChildSpawnHooks::default()
153    }
154}
155
156/// The results of running the spawn hooks.
157///
158/// This struct is sent to the new thread.
159/// It contains the inherited hooks and the closures to be run.
160#[ferrocene::prevalidated]
161#[derive(Default)]
162pub(super) struct ChildSpawnHooks {
163    hooks: SpawnHooks,
164    to_run: Vec<Box<dyn FnOnce() + Send>>,
165}
166
167impl ChildSpawnHooks {
168    // This is run on the newly spawned thread, directly at the start.
169    #[ferrocene::prevalidated]
170    pub(super) fn inherit_and_run(self) {
171        SPAWN_HOOKS.set(self.hooks);
172        for run in self.to_run {
173            run();
174        }
175    }
176}