std/thread/scoped.rs
1use super::Result;
2use super::builder::Builder;
3use super::current::current_or_unnamed;
4use super::lifecycle::{JoinInner, spawn_unchecked};
5use super::thread::Thread;
6use crate::marker::PhantomData;
7use crate::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
8use crate::sync::Arc;
9use crate::sync::atomic::{Atomic, AtomicBool, AtomicUsize, Ordering};
10use crate::{fmt, io};
11
12/// A scope to spawn scoped threads in.
13///
14/// See [`scope`] for details.
15#[stable(feature = "scoped_threads", since = "1.63.0")]
16pub struct Scope<'scope, 'env: 'scope> {
17 data: Arc<ScopeData>,
18 /// Invariance over 'scope, to make sure 'scope cannot shrink,
19 /// which is necessary for soundness.
20 ///
21 /// Without invariance, this would compile fine but be unsound:
22 ///
23 /// ```compile_fail,E0373
24 /// std::thread::scope(|s| {
25 /// s.spawn(|| {
26 /// let a = String::from("abcd");
27 /// s.spawn(|| println!("{a:?}")); // might run after `a` is dropped
28 /// });
29 /// });
30 /// ```
31 scope: PhantomData<&'scope mut &'scope ()>,
32 env: PhantomData<&'env mut &'env ()>,
33}
34
35/// An owned permission to join on a scoped thread (block on its termination).
36///
37/// See [`Scope::spawn`] for details.
38#[stable(feature = "scoped_threads", since = "1.63.0")]
39pub struct ScopedJoinHandle<'scope, T>(JoinInner<'scope, T>);
40
41pub(super) struct ScopeData {
42 num_running_threads: Atomic<usize>,
43 a_thread_panicked: Atomic<bool>,
44 main_thread: Thread,
45}
46
47impl ScopeData {
48 #[ferrocene::prevalidated]
49 pub(super) fn increment_num_running_threads(&self) {
50 // We check for 'overflow' with usize::MAX / 2, to make sure there's no
51 // chance it overflows to 0, which would result in unsoundness.
52 if self.num_running_threads.fetch_add(1, Ordering::Relaxed) > usize::MAX / 2 {
53 // This can only reasonably happen by mem::forget()'ing a lot of ScopedJoinHandles.
54 self.overflow();
55 }
56 }
57
58 #[ferrocene::prevalidated]
59 #[cold]
60 fn overflow(&self) {
61 self.decrement_num_running_threads(false);
62 panic!("too many running threads in thread scope");
63 }
64
65 #[ferrocene::prevalidated]
66 pub(super) fn decrement_num_running_threads(&self, panic: bool) {
67 if panic {
68 self.a_thread_panicked.store(true, Ordering::Relaxed);
69 }
70 if self.num_running_threads.fetch_sub(1, Ordering::Release) == 1 {
71 self.main_thread.unpark();
72 }
73 }
74}
75
76/// Creates a scope for spawning scoped threads.
77///
78/// The function passed to `scope` will be provided a [`Scope`] object,
79/// through which scoped threads can be [spawned][`Scope::spawn`].
80///
81/// Unlike non-scoped threads, scoped threads can borrow non-`'static` data,
82/// as the scope guarantees all threads will be joined at the end of the scope.
83///
84/// All threads spawned within the scope that haven't been manually joined
85/// will be automatically joined before this function returns.
86/// However, note that joining will only wait for the main function of these threads to finish; even
87/// when this function returns, destructors of thread-local variables in these threads might still
88/// be running.
89///
90/// # Panics
91///
92/// If any of the automatically joined threads panicked, this function will panic.
93///
94/// If you want to handle panics from spawned threads,
95/// [`join`][ScopedJoinHandle::join] them before the end of the scope.
96///
97/// # Example
98///
99/// ```
100/// use std::thread;
101///
102/// let mut a = vec![1, 2, 3];
103/// let mut x = 0;
104///
105/// thread::scope(|s| {
106/// s.spawn(|| {
107/// println!("hello from the first scoped thread");
108/// // We can borrow `a` here.
109/// dbg!(&a);
110/// });
111/// s.spawn(|| {
112/// println!("hello from the second scoped thread");
113/// // We can even mutably borrow `x` here,
114/// // because no other threads are using it.
115/// x += a[0] + a[2];
116/// });
117/// println!("hello from the main thread");
118/// });
119///
120/// // After the scope, we can modify and access our variables again:
121/// a.push(4);
122/// assert_eq!(x, a.len());
123/// ```
124///
125/// # Lifetimes
126///
127/// Scoped threads involve two lifetimes: `'scope` and `'env`.
128///
129/// The `'scope` lifetime represents the lifetime of the scope itself.
130/// That is: the time during which new scoped threads may be spawned,
131/// and also the time during which they might still be running.
132/// Once this lifetime ends, all scoped threads are joined.
133/// This lifetime starts within the `scope` function, before `f` (the argument to `scope`) starts.
134/// It ends after `f` returns and all scoped threads have been joined, but before `scope` returns.
135///
136/// The `'env` lifetime represents the lifetime of whatever is borrowed by the scoped threads.
137/// This lifetime must outlast the call to `scope`, and thus cannot be smaller than `'scope`.
138/// It can be as small as the call to `scope`, meaning that anything that outlives this call,
139/// such as local variables defined right before the scope, can be borrowed by the scoped threads.
140///
141/// The `'env: 'scope` bound is part of the definition of the `Scope` type.
142#[track_caller]
143#[stable(feature = "scoped_threads", since = "1.63.0")]
144pub fn scope<'env, F, T>(f: F) -> T
145where
146 F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T,
147{
148 // We put the `ScopeData` into an `Arc` so that other threads can finish their
149 // `decrement_num_running_threads` even after this function returns.
150 let scope = Scope {
151 data: Arc::new(ScopeData {
152 num_running_threads: AtomicUsize::new(0),
153 main_thread: current_or_unnamed(),
154 a_thread_panicked: AtomicBool::new(false),
155 }),
156 env: PhantomData,
157 scope: PhantomData,
158 };
159
160 // Run `f`, but catch panics so we can make sure to wait for all the threads to join.
161 let result = catch_unwind(AssertUnwindSafe(|| f(&scope)));
162
163 // Wait until all the threads are finished.
164 while scope.data.num_running_threads.load(Ordering::Acquire) != 0 {
165 // SAFETY: this is the main thread, the handle belongs to us.
166 unsafe { scope.data.main_thread.park() };
167 }
168
169 // Throw any panic from `f`, or the return value of `f` if no thread panicked.
170 match result {
171 Err(e) => resume_unwind(e),
172 Ok(_) if scope.data.a_thread_panicked.load(Ordering::Relaxed) => {
173 panic!("a scoped thread panicked")
174 }
175 Ok(result) => result,
176 }
177}
178
179impl<'scope, 'env> Scope<'scope, 'env> {
180 /// Spawns a new thread within a scope, returning a [`ScopedJoinHandle`] for it.
181 ///
182 /// Unlike non-scoped threads, threads spawned with this function may
183 /// borrow non-`'static` data from outside the scope. See [`scope`] for
184 /// details.
185 ///
186 /// The join handle provides a [`join`] method that can be used to join the spawned
187 /// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
188 /// the panic payload.
189 ///
190 /// If the join handle is dropped, the spawned thread will be implicitly joined at the
191 /// end of the scope. In that case, if the spawned thread panics, [`scope`] will
192 /// panic after all threads are joined.
193 ///
194 /// This function creates a thread with the default parameters of [`Builder`].
195 /// To specify the new thread's stack size or the name, use [`Builder::spawn_scoped`].
196 ///
197 /// # Panics
198 ///
199 /// Panics if the OS fails to create a thread; use [`Builder::spawn_scoped`]
200 /// to recover from such errors.
201 ///
202 /// [`join`]: ScopedJoinHandle::join
203 #[stable(feature = "scoped_threads", since = "1.63.0")]
204 pub fn spawn<F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T>
205 where
206 F: FnOnce() -> T + Send + 'scope,
207 T: Send + 'scope,
208 {
209 Builder::new().spawn_scoped(self, f).expect("failed to spawn thread")
210 }
211}
212
213impl Builder {
214 /// Spawns a new scoped thread using the settings set through this `Builder`.
215 ///
216 /// Unlike [`Scope::spawn`], this method yields an [`io::Result`] to
217 /// capture any failure to create the thread at the OS level.
218 ///
219 /// # Panics
220 ///
221 /// Panics if a thread name was set and it contained null bytes.
222 ///
223 /// # Example
224 ///
225 /// ```
226 /// use std::thread;
227 ///
228 /// let mut a = vec![1, 2, 3];
229 /// let mut x = 0;
230 ///
231 /// thread::scope(|s| {
232 /// thread::Builder::new()
233 /// .name("first".to_string())
234 /// .spawn_scoped(s, ||
235 /// {
236 /// println!("hello from the {:?} scoped thread", thread::current().name());
237 /// // We can borrow `a` here.
238 /// dbg!(&a);
239 /// })
240 /// .unwrap();
241 /// thread::Builder::new()
242 /// .name("second".to_string())
243 /// .spawn_scoped(s, ||
244 /// {
245 /// println!("hello from the {:?} scoped thread", thread::current().name());
246 /// // We can even mutably borrow `x` here,
247 /// // because no other threads are using it.
248 /// x += a[0] + a[2];
249 /// })
250 /// .unwrap();
251 /// println!("hello from the main thread");
252 /// });
253 ///
254 /// // After the scope, we can modify and access our variables again:
255 /// a.push(4);
256 /// assert_eq!(x, a.len());
257 /// ```
258 #[stable(feature = "scoped_threads", since = "1.63.0")]
259 pub fn spawn_scoped<'scope, 'env, F, T>(
260 self,
261 scope: &'scope Scope<'scope, 'env>,
262 f: F,
263 ) -> io::Result<ScopedJoinHandle<'scope, T>>
264 where
265 F: FnOnce() -> T + Send + 'scope,
266 T: Send + 'scope,
267 {
268 let Builder { name, stack_size, no_hooks } = self;
269 Ok(ScopedJoinHandle(unsafe {
270 spawn_unchecked(name, stack_size, no_hooks, Some(scope.data.clone()), f)
271 }?))
272 }
273}
274
275impl<'scope, T> ScopedJoinHandle<'scope, T> {
276 /// Extracts a handle to the underlying thread.
277 ///
278 /// # Examples
279 ///
280 /// ```
281 /// use std::thread;
282 ///
283 /// thread::scope(|s| {
284 /// let t = s.spawn(|| {
285 /// println!("hello");
286 /// });
287 /// println!("thread id: {:?}", t.thread().id());
288 /// });
289 /// ```
290 #[must_use]
291 #[stable(feature = "scoped_threads", since = "1.63.0")]
292 pub fn thread(&self) -> &Thread {
293 self.0.thread()
294 }
295
296 /// Waits for the associated thread to finish.
297 ///
298 /// This function will return immediately if the associated thread has already finished.
299 /// Otherwise, it fully waits for the thread to finish, including all destructors
300 /// for thread-local variables that might be running after the main function of the thread.
301 ///
302 /// In terms of [atomic memory orderings], the completion of the associated
303 /// thread synchronizes with this function returning.
304 /// In other words, all operations performed by that thread
305 /// [happen before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses)
306 /// all operations that happen after `join` returns.
307 ///
308 /// If the associated thread panics, [`Err`] is returned with the panic payload.
309 ///
310 /// [atomic memory orderings]: crate::sync::atomic
311 ///
312 /// # Examples
313 ///
314 /// ```
315 /// use std::thread;
316 ///
317 /// thread::scope(|s| {
318 /// let t = s.spawn(|| {
319 /// panic!("oh no");
320 /// });
321 /// assert!(t.join().is_err());
322 /// });
323 /// ```
324 #[stable(feature = "scoped_threads", since = "1.63.0")]
325 pub fn join(self) -> Result<T> {
326 self.0.join()
327 }
328
329 /// Checks if the associated thread has finished running its main function.
330 ///
331 /// `is_finished` supports implementing a non-blocking join operation, by checking
332 /// `is_finished`, and calling `join` if it returns `true`. This function does not block. To
333 /// block while waiting on the thread to finish, use [`join`][Self::join].
334 ///
335 /// This might return `true` for a brief moment after the thread's main
336 /// function has returned, but before the thread itself has stopped running.
337 /// However, once this returns `true`, [`join`][Self::join] can be expected
338 /// to return quickly, without blocking for any significant amount of time.
339 #[stable(feature = "scoped_threads", since = "1.63.0")]
340 pub fn is_finished(&self) -> bool {
341 self.0.is_finished()
342 }
343}
344
345#[stable(feature = "scoped_threads", since = "1.63.0")]
346impl fmt::Debug for Scope<'_, '_> {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 f.debug_struct("Scope")
349 .field("num_running_threads", &self.data.num_running_threads.load(Ordering::Relaxed))
350 .field("a_thread_panicked", &self.data.a_thread_panicked.load(Ordering::Relaxed))
351 .field("main_thread", &self.data.main_thread)
352 .finish_non_exhaustive()
353 }
354}
355
356#[stable(feature = "scoped_threads", since = "1.63.0")]
357impl<'scope, T> fmt::Debug for ScopedJoinHandle<'scope, T> {
358 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359 f.debug_struct("ScopedJoinHandle").finish_non_exhaustive()
360 }
361}