1 use super::{current, park, Builder, JoinInner, Result, Thread};
4 use crate::marker::PhantomData;
5 use crate::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
6 use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
9 /// A scope to spawn scoped threads in.
11 /// See [`scope`] for details.
12 pub struct Scope<'env> {
14 /// Invariance over 'env, to make sure 'env cannot shrink,
15 /// which is necessary for soundness.
17 /// Without invariance, this would compile fine but be unsound:
20 /// #![feature(scoped_threads)]
22 /// std::thread::scope(|s| {
24 /// let a = String::from("abcd");
25 /// s.spawn(|_| println!("{:?}", a)); // might run after `a` is dropped
29 env: PhantomData<&'env mut &'env ()>,
32 /// An owned permission to join on a scoped thread (block on its termination).
34 /// See [`Scope::spawn`] for details.
35 pub struct ScopedJoinHandle<'scope, T>(JoinInner<'scope, T>);
37 pub(super) struct ScopeData {
38 num_running_threads: AtomicUsize,
39 a_thread_panicked: AtomicBool,
44 pub(super) fn increment_num_running_threads(&self) {
45 // We check for 'overflow' with usize::MAX / 2, to make sure there's no
46 // chance it overflows to 0, which would result in unsoundness.
47 if self.num_running_threads.fetch_add(1, Ordering::Relaxed) > usize::MAX / 2 {
48 // This can only reasonably happen by mem::forget()'ing many many ScopedJoinHandles.
49 self.decrement_num_running_threads(false);
50 panic!("too many running threads in thread scope");
53 pub(super) fn decrement_num_running_threads(&self, panic: bool) {
55 self.a_thread_panicked.store(true, Ordering::Relaxed);
57 if self.num_running_threads.fetch_sub(1, Ordering::Release) == 1 {
58 self.main_thread.unpark();
63 /// Create a scope for spawning scoped threads.
65 /// The function passed to `scope` will be provided a [`Scope`] object,
66 /// through which scoped threads can be [spawned][`Scope::spawn`].
68 /// Unlike non-scoped threads, scoped threads can borrow non-`'static` data,
69 /// as the scope guarantees all threads will be joined at the end of the scope.
71 /// All threads spawned within the scope that haven't been manually joined
72 /// will be automatically joined before this function returns.
76 /// If any of the automatically joined threads panicked, this function will panic.
78 /// If you want to handle panics from spawned threads,
79 /// [`join`][ScopedJoinHandle::join] them before the end of the scope.
84 /// #![feature(scoped_threads)]
87 /// let mut a = vec![1, 2, 3];
90 /// thread::scope(|s| {
92 /// println!("hello from the first scoped thread");
93 /// // We can borrow `a` here.
97 /// println!("hello from the second scoped thread");
98 /// // We can even mutably borrow `x` here,
99 /// // because no other threads are using it.
100 /// x += a[0] + a[2];
102 /// println!("hello from the main thread");
105 /// // After the scope, we can modify and access our variables again:
107 /// assert_eq!(x, a.len());
110 pub fn scope<'env, F, T>(f: F) -> T
112 F: FnOnce(&Scope<'env>) -> T,
116 num_running_threads: AtomicUsize::new(0),
117 main_thread: current(),
118 a_thread_panicked: AtomicBool::new(false),
123 // Run `f`, but catch panics so we can make sure to wait for all the threads to join.
124 let result = catch_unwind(AssertUnwindSafe(|| f(&scope)));
126 // Wait until all the threads are finished.
127 while scope.data.num_running_threads.load(Ordering::Acquire) != 0 {
131 // Throw any panic from `f`, or the return value of `f` if no thread panicked.
133 Err(e) => resume_unwind(e),
134 Ok(_) if scope.data.a_thread_panicked.load(Ordering::Relaxed) => {
135 panic!("a scoped thread panicked")
137 Ok(result) => result,
141 impl<'env> Scope<'env> {
142 /// Spawns a new thread within a scope, returning a [`ScopedJoinHandle`] for it.
144 /// Unlike non-scoped threads, threads spawned with this function may
145 /// borrow non-`'static` data from the outside the scope. See [`scope`] for
148 /// The join handle provides a [`join`] method that can be used to join the spawned
149 /// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
150 /// the panic payload.
152 /// If the join handle is dropped, the spawned thread will implicitly joined at the
153 /// end of the scope. In that case, if the spawned thread panics, [`scope`] will
154 /// panic after all threads are joined.
156 /// This call will create a thread using default parameters of [`Builder`].
157 /// If you want to specify the stack size or the name of the thread, use
158 /// [`Builder::spawn_scoped`] instead.
162 /// Panics if the OS fails to create a thread; use [`Builder::spawn_scoped`]
163 /// to recover from such errors.
165 /// [`join`]: ScopedJoinHandle::join
166 pub fn spawn<'scope, F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T>
168 F: FnOnce(&Scope<'env>) -> T + Send + 'env,
171 Builder::new().spawn_scoped(self, f).expect("failed to spawn thread")
176 /// Spawns a new scoped thread using the settings set through this `Builder`.
178 /// Unlike [`Scope::spawn`], this method yields an [`io::Result`] to
179 /// capture any failure to create the thread at the OS level.
181 /// [`io::Result`]: crate::io::Result
185 /// Panics if a thread name was set and it contained null bytes.
190 /// #![feature(scoped_threads)]
193 /// let mut a = vec![1, 2, 3];
196 /// thread::scope(|s| {
197 /// thread::Builder::new()
198 /// .name("first".to_string())
199 /// .spawn_scoped(s, |_|
201 /// println!("hello from the {:?} scoped thread", thread::current().name());
202 /// // We can borrow `a` here.
206 /// thread::Builder::new()
207 /// .name("second".to_string())
208 /// .spawn_scoped(s, |_|
210 /// println!("hello from the {:?} scoped thread", thread::current().name());
211 /// // We can even mutably borrow `x` here,
212 /// // because no other threads are using it.
213 /// x += a[0] + a[2];
216 /// println!("hello from the main thread");
219 /// // After the scope, we can modify and access our variables again:
221 /// assert_eq!(x, a.len());
223 pub fn spawn_scoped<'scope, 'env, F, T>(
225 scope: &'scope Scope<'env>,
227 ) -> io::Result<ScopedJoinHandle<'scope, T>>
229 F: FnOnce(&Scope<'env>) -> T + Send + 'env,
232 Ok(ScopedJoinHandle(unsafe { self.spawn_unchecked_(|| f(scope), Some(&scope.data)) }?))
236 impl<'scope, T> ScopedJoinHandle<'scope, T> {
237 /// Extracts a handle to the underlying thread.
242 /// #![feature(scoped_threads)]
243 /// #![feature(thread_is_running)]
247 /// thread::scope(|s| {
248 /// let t = s.spawn(|_| {
249 /// println!("hello");
251 /// println!("thread id: {:?}", t.thread().id());
255 pub fn thread(&self) -> &Thread {
259 /// Waits for the associated thread to finish.
261 /// This function will return immediately if the associated thread has already finished.
263 /// In terms of [atomic memory orderings], the completion of the associated
264 /// thread synchronizes with this function returning.
265 /// In other words, all operations performed by that thread
266 /// [happen before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses)
267 /// all operations that happen after `join` returns.
269 /// If the associated thread panics, [`Err`] is returned with the panic payload.
271 /// [atomic memory orderings]: crate::sync::atomic
276 /// #![feature(scoped_threads)]
277 /// #![feature(thread_is_running)]
281 /// thread::scope(|s| {
282 /// let t = s.spawn(|_| {
285 /// assert!(t.join().is_err());
288 pub fn join(self) -> Result<T> {
292 /// Checks if the associated thread is still running its main function.
294 /// This might return `false` for a brief moment after the thread's main
295 /// function has returned, but before the thread itself has stopped running.
296 #[unstable(feature = "thread_is_running", issue = "90470")]
297 pub fn is_running(&self) -> bool {
298 Arc::strong_count(&self.0.packet) > 1
302 impl<'env> fmt::Debug for Scope<'env> {
303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304 f.debug_struct("Scope")
305 .field("num_running_threads", &self.data.num_running_threads.load(Ordering::Relaxed))
306 .field("a_thread_panicked", &self.data.a_thread_panicked.load(Ordering::Relaxed))
307 .field("main_thread", &self.data.main_thread)
308 .finish_non_exhaustive()
312 impl<'scope, T> fmt::Debug for ScopedJoinHandle<'scope, T> {
313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314 f.debug_struct("ScopedJoinHandle").finish_non_exhaustive()