]> git.lizzy.rs Git - rust.git/blob - library/std/src/thread/mod.rs
Fix soundness issue in scoped threads.
[rust.git] / library / std / src / thread / mod.rs
1 //! Native threads.
2 //!
3 //! ## The threading model
4 //!
5 //! An executing Rust program consists of a collection of native OS threads,
6 //! each with their own stack and local state. Threads can be named, and
7 //! provide some built-in support for low-level synchronization.
8 //!
9 //! Communication between threads can be done through
10 //! [channels], Rust's message-passing types, along with [other forms of thread
11 //! synchronization](../../std/sync/index.html) and shared-memory data
12 //! structures. In particular, types that are guaranteed to be
13 //! threadsafe are easily shared between threads using the
14 //! atomically-reference-counted container, [`Arc`].
15 //!
16 //! Fatal logic errors in Rust cause *thread panic*, during which
17 //! a thread will unwind the stack, running destructors and freeing
18 //! owned resources. While not meant as a 'try/catch' mechanism, panics
19 //! in Rust can nonetheless be caught (unless compiling with `panic=abort`) with
20 //! [`catch_unwind`](../../std/panic/fn.catch_unwind.html) and recovered
21 //! from, or alternatively be resumed with
22 //! [`resume_unwind`](../../std/panic/fn.resume_unwind.html). If the panic
23 //! is not caught the thread will exit, but the panic may optionally be
24 //! detected from a different thread with [`join`]. If the main thread panics
25 //! without the panic being caught, the application will exit with a
26 //! non-zero exit code.
27 //!
28 //! When the main thread of a Rust program terminates, the entire program shuts
29 //! down, even if other threads are still running. However, this module provides
30 //! convenient facilities for automatically waiting for the termination of a
31 //! thread (i.e., join).
32 //!
33 //! ## Spawning a thread
34 //!
35 //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
36 //!
37 //! ```rust
38 //! use std::thread;
39 //!
40 //! thread::spawn(move || {
41 //!     // some work here
42 //! });
43 //! ```
44 //!
45 //! In this example, the spawned thread is "detached," which means that there is
46 //! no way for the program to learn when the spawned thread completes or otherwise
47 //! terminates.
48 //!
49 //! To learn when a thread completes, it is necessary to capture the [`JoinHandle`]
50 //! object that is returned by the call to [`spawn`], which provides
51 //! a `join` method that allows the caller to wait for the completion of the
52 //! spawned thread:
53 //!
54 //! ```rust
55 //! use std::thread;
56 //!
57 //! let thread_join_handle = thread::spawn(move || {
58 //!     // some work here
59 //! });
60 //! // some work here
61 //! let res = thread_join_handle.join();
62 //! ```
63 //!
64 //! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
65 //! value produced by the spawned thread, or [`Err`] of the value given to
66 //! a call to [`panic!`] if the thread panicked.
67 //!
68 //! Note that there is no parent/child relationship between a thread that spawns a
69 //! new thread and the thread being spawned.  In particular, the spawned thread may or
70 //! may not outlive the spawning thread, unless the spawning thread is the main thread.
71 //!
72 //! ## Configuring threads
73 //!
74 //! A new thread can be configured before it is spawned via the [`Builder`] type,
75 //! which currently allows you to set the name and stack size for the thread:
76 //!
77 //! ```rust
78 //! # #![allow(unused_must_use)]
79 //! use std::thread;
80 //!
81 //! thread::Builder::new().name("thread1".to_string()).spawn(move || {
82 //!     println!("Hello, world!");
83 //! });
84 //! ```
85 //!
86 //! ## The `Thread` type
87 //!
88 //! Threads are represented via the [`Thread`] type, which you can get in one of
89 //! two ways:
90 //!
91 //! * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
92 //!   function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
93 //! * By requesting the current thread, using the [`thread::current`] function.
94 //!
95 //! The [`thread::current`] function is available even for threads not spawned
96 //! by the APIs of this module.
97 //!
98 //! ## Thread-local storage
99 //!
100 //! This module also provides an implementation of thread-local storage for Rust
101 //! programs. Thread-local storage is a method of storing data into a global
102 //! variable that each thread in the program will have its own copy of.
103 //! Threads do not share this data, so accesses do not need to be synchronized.
104 //!
105 //! A thread-local key owns the value it contains and will destroy the value when the
106 //! thread exits. It is created with the [`thread_local!`] macro and can contain any
107 //! value that is `'static` (no borrowed pointers). It provides an accessor function,
108 //! [`with`], that yields a shared reference to the value to the specified
109 //! closure. Thread-local keys allow only shared access to values, as there would be no
110 //! way to guarantee uniqueness if mutable borrows were allowed. Most values
111 //! will want to make use of some form of **interior mutability** through the
112 //! [`Cell`] or [`RefCell`] types.
113 //!
114 //! ## Naming threads
115 //!
116 //! Threads are able to have associated names for identification purposes. By default, spawned
117 //! threads are unnamed. To specify a name for a thread, build the thread with [`Builder`] and pass
118 //! the desired thread name to [`Builder::name`]. To retrieve the thread name from within the
119 //! thread, use [`Thread::name`]. A couple examples of where the name of a thread gets used:
120 //!
121 //! * If a panic occurs in a named thread, the thread name will be printed in the panic message.
122 //! * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in
123 //!   unix-like platforms).
124 //!
125 //! ## Stack size
126 //!
127 //! The default stack size for spawned threads is 2 MiB, though this particular stack size is
128 //! subject to change in the future. There are two ways to manually specify the stack size for
129 //! spawned threads:
130 //!
131 //! * Build the thread with [`Builder`] and pass the desired stack size to [`Builder::stack_size`].
132 //! * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack
133 //!   size (in bytes). Note that setting [`Builder::stack_size`] will override this.
134 //!
135 //! Note that the stack size of the main thread is *not* determined by Rust.
136 //!
137 //! [channels]: crate::sync::mpsc
138 //! [`join`]: JoinHandle::join
139 //! [`Result`]: crate::result::Result
140 //! [`Ok`]: crate::result::Result::Ok
141 //! [`Err`]: crate::result::Result::Err
142 //! [`thread::current`]: current
143 //! [`thread::Result`]: Result
144 //! [`unpark`]: Thread::unpark
145 //! [`thread::park_timeout`]: park_timeout
146 //! [`Cell`]: crate::cell::Cell
147 //! [`RefCell`]: crate::cell::RefCell
148 //! [`with`]: LocalKey::with
149
150 #![stable(feature = "rust1", since = "1.0.0")]
151 #![deny(unsafe_op_in_unsafe_fn)]
152
153 #[cfg(all(test, not(target_os = "emscripten")))]
154 mod tests;
155
156 use crate::any::Any;
157 use crate::cell::UnsafeCell;
158 use crate::ffi::{CStr, CString};
159 use crate::fmt;
160 use crate::io;
161 use crate::mem;
162 use crate::num::NonZeroU64;
163 use crate::num::NonZeroUsize;
164 use crate::panic;
165 use crate::panicking;
166 use crate::str;
167 use crate::sync::Arc;
168 use crate::sys::thread as imp;
169 use crate::sys_common::mutex;
170 use crate::sys_common::thread;
171 use crate::sys_common::thread_info;
172 use crate::sys_common::thread_parker::Parker;
173 use crate::sys_common::{AsInner, IntoInner};
174 use crate::time::Duration;
175
176 ////////////////////////////////////////////////////////////////////////////////
177 // Thread-local storage
178 ////////////////////////////////////////////////////////////////////////////////
179
180 #[macro_use]
181 mod local;
182
183 #[unstable(feature = "scoped_threads", issue = "93203")]
184 mod scoped;
185
186 #[unstable(feature = "scoped_threads", issue = "93203")]
187 pub use scoped::{scope, Scope, ScopedJoinHandle};
188
189 #[stable(feature = "rust1", since = "1.0.0")]
190 pub use self::local::{AccessError, LocalKey};
191
192 // The types used by the thread_local! macro to access TLS keys. Note that there
193 // are two types, the "OS" type and the "fast" type. The OS thread local key
194 // type is accessed via platform-specific API calls and is slow, while the fast
195 // key type is accessed via code generated via LLVM, where TLS keys are set up
196 // by the elf linker. Note that the OS TLS type is always available: on macOS
197 // the standard library is compiled with support for older platform versions
198 // where fast TLS was not available; end-user code is compiled with fast TLS
199 // where available, but both are needed.
200
201 #[unstable(feature = "libstd_thread_internals", issue = "none")]
202 #[cfg(target_thread_local)]
203 #[doc(hidden)]
204 pub use self::local::fast::Key as __FastLocalKeyInner;
205 #[unstable(feature = "libstd_thread_internals", issue = "none")]
206 #[doc(hidden)]
207 pub use self::local::os::Key as __OsLocalKeyInner;
208 #[unstable(feature = "libstd_thread_internals", issue = "none")]
209 #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
210 #[doc(hidden)]
211 pub use self::local::statik::Key as __StaticLocalKeyInner;
212
213 ////////////////////////////////////////////////////////////////////////////////
214 // Builder
215 ////////////////////////////////////////////////////////////////////////////////
216
217 /// Thread factory, which can be used in order to configure the properties of
218 /// a new thread.
219 ///
220 /// Methods can be chained on it in order to configure it.
221 ///
222 /// The two configurations available are:
223 ///
224 /// - [`name`]: specifies an [associated name for the thread][naming-threads]
225 /// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
226 ///
227 /// The [`spawn`] method will take ownership of the builder and create an
228 /// [`io::Result`] to the thread handle with the given configuration.
229 ///
230 /// The [`thread::spawn`] free function uses a `Builder` with default
231 /// configuration and [`unwrap`]s its return value.
232 ///
233 /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
234 /// to recover from a failure to launch a thread, indeed the free function will
235 /// panic where the `Builder` method will return a [`io::Result`].
236 ///
237 /// # Examples
238 ///
239 /// ```
240 /// use std::thread;
241 ///
242 /// let builder = thread::Builder::new();
243 ///
244 /// let handler = builder.spawn(|| {
245 ///     // thread code
246 /// }).unwrap();
247 ///
248 /// handler.join().unwrap();
249 /// ```
250 ///
251 /// [`stack_size`]: Builder::stack_size
252 /// [`name`]: Builder::name
253 /// [`spawn`]: Builder::spawn
254 /// [`thread::spawn`]: spawn
255 /// [`io::Result`]: crate::io::Result
256 /// [`unwrap`]: crate::result::Result::unwrap
257 /// [naming-threads]: ./index.html#naming-threads
258 /// [stack-size]: ./index.html#stack-size
259 #[must_use = "must eventually spawn the thread"]
260 #[stable(feature = "rust1", since = "1.0.0")]
261 #[derive(Debug)]
262 pub struct Builder {
263     // A name for the thread-to-be, for identification in panic messages
264     name: Option<String>,
265     // The size of the stack for the spawned thread in bytes
266     stack_size: Option<usize>,
267 }
268
269 impl Builder {
270     /// Generates the base configuration for spawning a thread, from which
271     /// configuration methods can be chained.
272     ///
273     /// # Examples
274     ///
275     /// ```
276     /// use std::thread;
277     ///
278     /// let builder = thread::Builder::new()
279     ///                               .name("foo".into())
280     ///                               .stack_size(32 * 1024);
281     ///
282     /// let handler = builder.spawn(|| {
283     ///     // thread code
284     /// }).unwrap();
285     ///
286     /// handler.join().unwrap();
287     /// ```
288     #[stable(feature = "rust1", since = "1.0.0")]
289     pub fn new() -> Builder {
290         Builder { name: None, stack_size: None }
291     }
292
293     /// Names the thread-to-be. Currently the name is used for identification
294     /// only in panic messages.
295     ///
296     /// The name must not contain null bytes (`\0`).
297     ///
298     /// For more information about named threads, see
299     /// [this module-level documentation][naming-threads].
300     ///
301     /// # Examples
302     ///
303     /// ```
304     /// use std::thread;
305     ///
306     /// let builder = thread::Builder::new()
307     ///     .name("foo".into());
308     ///
309     /// let handler = builder.spawn(|| {
310     ///     assert_eq!(thread::current().name(), Some("foo"))
311     /// }).unwrap();
312     ///
313     /// handler.join().unwrap();
314     /// ```
315     ///
316     /// [naming-threads]: ./index.html#naming-threads
317     #[stable(feature = "rust1", since = "1.0.0")]
318     pub fn name(mut self, name: String) -> Builder {
319         self.name = Some(name);
320         self
321     }
322
323     /// Sets the size of the stack (in bytes) for the new thread.
324     ///
325     /// The actual stack size may be greater than this value if
326     /// the platform specifies a minimal stack size.
327     ///
328     /// For more information about the stack size for threads, see
329     /// [this module-level documentation][stack-size].
330     ///
331     /// # Examples
332     ///
333     /// ```
334     /// use std::thread;
335     ///
336     /// let builder = thread::Builder::new().stack_size(32 * 1024);
337     /// ```
338     ///
339     /// [stack-size]: ./index.html#stack-size
340     #[stable(feature = "rust1", since = "1.0.0")]
341     pub fn stack_size(mut self, size: usize) -> Builder {
342         self.stack_size = Some(size);
343         self
344     }
345
346     /// Spawns a new thread by taking ownership of the `Builder`, and returns an
347     /// [`io::Result`] to its [`JoinHandle`].
348     ///
349     /// The spawned thread may outlive the caller (unless the caller thread
350     /// is the main thread; the whole process is terminated when the main
351     /// thread finishes). The join handle can be used to block on
352     /// termination of the spawned thread, including recovering its panics.
353     ///
354     /// For a more complete documentation see [`thread::spawn`][`spawn`].
355     ///
356     /// # Errors
357     ///
358     /// Unlike the [`spawn`] free function, this method yields an
359     /// [`io::Result`] to capture any failure to create the thread at
360     /// the OS level.
361     ///
362     /// [`io::Result`]: crate::io::Result
363     ///
364     /// # Panics
365     ///
366     /// Panics if a thread name was set and it contained null bytes.
367     ///
368     /// # Examples
369     ///
370     /// ```
371     /// use std::thread;
372     ///
373     /// let builder = thread::Builder::new();
374     ///
375     /// let handler = builder.spawn(|| {
376     ///     // thread code
377     /// }).unwrap();
378     ///
379     /// handler.join().unwrap();
380     /// ```
381     #[stable(feature = "rust1", since = "1.0.0")]
382     pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
383     where
384         F: FnOnce() -> T,
385         F: Send + 'static,
386         T: Send + 'static,
387     {
388         unsafe { self.spawn_unchecked(f) }
389     }
390
391     /// Spawns a new thread without any lifetime restrictions by taking ownership
392     /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
393     ///
394     /// The spawned thread may outlive the caller (unless the caller thread
395     /// is the main thread; the whole process is terminated when the main
396     /// thread finishes). The join handle can be used to block on
397     /// termination of the spawned thread, including recovering its panics.
398     ///
399     /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
400     /// except for the relaxed lifetime bounds, which render it unsafe.
401     /// For a more complete documentation see [`thread::spawn`][`spawn`].
402     ///
403     /// # Errors
404     ///
405     /// Unlike the [`spawn`] free function, this method yields an
406     /// [`io::Result`] to capture any failure to create the thread at
407     /// the OS level.
408     ///
409     /// # Panics
410     ///
411     /// Panics if a thread name was set and it contained null bytes.
412     ///
413     /// # Safety
414     ///
415     /// The caller has to ensure that the spawned thread does not outlive any
416     /// references in the supplied thread closure and its return type.
417     /// This can be guaranteed in two ways:
418     ///
419     /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
420     /// data is dropped
421     /// - use only types with `'static` lifetime bounds, i.e., those with no or only
422     /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
423     /// and [`thread::spawn`][`spawn`] enforce this property statically)
424     ///
425     /// # Examples
426     ///
427     /// ```
428     /// #![feature(thread_spawn_unchecked)]
429     /// use std::thread;
430     ///
431     /// let builder = thread::Builder::new();
432     ///
433     /// let x = 1;
434     /// let thread_x = &x;
435     ///
436     /// let handler = unsafe {
437     ///     builder.spawn_unchecked(move || {
438     ///         println!("x = {}", *thread_x);
439     ///     }).unwrap()
440     /// };
441     ///
442     /// // caller has to ensure `join()` is called, otherwise
443     /// // it is possible to access freed memory if `x` gets
444     /// // dropped before the thread closure is executed!
445     /// handler.join().unwrap();
446     /// ```
447     ///
448     /// [`io::Result`]: crate::io::Result
449     #[unstable(feature = "thread_spawn_unchecked", issue = "55132")]
450     pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>>
451     where
452         F: FnOnce() -> T,
453         F: Send + 'a,
454         T: Send + 'a,
455     {
456         Ok(JoinHandle(unsafe { self.spawn_unchecked_(f, None) }?))
457     }
458
459     unsafe fn spawn_unchecked_<'a, 'scope, F, T>(
460         self,
461         f: F,
462         scope_data: Option<&'scope scoped::ScopeData>,
463     ) -> io::Result<JoinInner<'scope, T>>
464     where
465         F: FnOnce() -> T,
466         F: Send + 'a,
467         T: Send + 'a,
468         'scope: 'a,
469     {
470         let Builder { name, stack_size } = self;
471
472         let stack_size = stack_size.unwrap_or_else(thread::min_stack);
473
474         let my_thread = Thread::new(name.map(|name| {
475             CString::new(name).expect("thread name may not contain interior null bytes")
476         }));
477         let their_thread = my_thread.clone();
478
479         let my_packet: Arc<Packet<'scope, T>> =
480             Arc::new(Packet { scope: scope_data, result: UnsafeCell::new(None) });
481         let their_packet = my_packet.clone();
482
483         let output_capture = crate::io::set_output_capture(None);
484         crate::io::set_output_capture(output_capture.clone());
485
486         let main = move || {
487             if let Some(name) = their_thread.cname() {
488                 imp::Thread::set_name(name);
489             }
490
491             crate::io::set_output_capture(output_capture);
492
493             // SAFETY: the stack guard passed is the one for the current thread.
494             // This means the current thread's stack and the new thread's stack
495             // are properly set and protected from each other.
496             thread_info::set(unsafe { imp::guard::current() }, their_thread);
497             let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
498                 crate::sys_common::backtrace::__rust_begin_short_backtrace(f)
499             }));
500             // SAFETY: `their_packet` as been built just above and moved by the
501             // closure (it is an Arc<...>) and `my_packet` will be stored in the
502             // same `JoinInner` as this closure meaning the mutation will be
503             // safe (not modify it and affect a value far away).
504             unsafe { *their_packet.result.get() = Some(try_result) };
505         };
506
507         if let Some(scope_data) = scope_data {
508             scope_data.increment_num_running_threads();
509         }
510
511         Ok(JoinInner {
512             // SAFETY:
513             //
514             // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
515             // through FFI or otherwise used with low-level threading primitives that have no
516             // notion of or way to enforce lifetimes.
517             //
518             // As mentioned in the `Safety` section of this function's documentation, the caller of
519             // this function needs to guarantee that the passed-in lifetime is sufficiently long
520             // for the lifetime of the thread.
521             //
522             // Similarly, the `sys` implementation must guarantee that no references to the closure
523             // exist after the thread has terminated, which is signaled by `Thread::join`
524             // returning.
525             native: unsafe {
526                 imp::Thread::new(
527                     stack_size,
528                     mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(
529                         Box::new(main),
530                     ),
531                 )?
532             },
533             thread: my_thread,
534             packet: my_packet,
535         })
536     }
537 }
538
539 ////////////////////////////////////////////////////////////////////////////////
540 // Free functions
541 ////////////////////////////////////////////////////////////////////////////////
542
543 /// Spawns a new thread, returning a [`JoinHandle`] for it.
544 ///
545 /// The join handle provides a [`join`] method that can be used to join the spawned
546 /// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
547 /// the argument given to [`panic!`].
548 ///
549 /// If the join handle is dropped, the spawned thread will implicitly be *detached*.
550 /// In this case, the spawned thread may no longer be joined.
551 /// (It is the responsibility of the program to either eventually join threads it
552 /// creates or detach them; otherwise, a resource leak will result.)
553 ///
554 /// This call will create a thread using default parameters of [`Builder`], if you
555 /// want to specify the stack size or the name of the thread, use this API
556 /// instead.
557 ///
558 /// As you can see in the signature of `spawn` there are two constraints on
559 /// both the closure given to `spawn` and its return value, let's explain them:
560 ///
561 /// - The `'static` constraint means that the closure and its return value
562 ///   must have a lifetime of the whole program execution. The reason for this
563 ///   is that threads can outlive the lifetime they have been created in.
564 ///
565 ///   Indeed if the thread, and by extension its return value, can outlive their
566 ///   caller, we need to make sure that they will be valid afterwards, and since
567 ///   we *can't* know when it will return we need to have them valid as long as
568 ///   possible, that is until the end of the program, hence the `'static`
569 ///   lifetime.
570 /// - The [`Send`] constraint is because the closure will need to be passed
571 ///   *by value* from the thread where it is spawned to the new thread. Its
572 ///   return value will need to be passed from the new thread to the thread
573 ///   where it is `join`ed.
574 ///   As a reminder, the [`Send`] marker trait expresses that it is safe to be
575 ///   passed from thread to thread. [`Sync`] expresses that it is safe to have a
576 ///   reference be passed from thread to thread.
577 ///
578 /// # Panics
579 ///
580 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
581 /// to recover from such errors.
582 ///
583 /// # Examples
584 ///
585 /// Creating a thread.
586 ///
587 /// ```
588 /// use std::thread;
589 ///
590 /// let handler = thread::spawn(|| {
591 ///     // thread code
592 /// });
593 ///
594 /// handler.join().unwrap();
595 /// ```
596 ///
597 /// As mentioned in the module documentation, threads are usually made to
598 /// communicate using [`channels`], here is how it usually looks.
599 ///
600 /// This example also shows how to use `move`, in order to give ownership
601 /// of values to a thread.
602 ///
603 /// ```
604 /// use std::thread;
605 /// use std::sync::mpsc::channel;
606 ///
607 /// let (tx, rx) = channel();
608 ///
609 /// let sender = thread::spawn(move || {
610 ///     tx.send("Hello, thread".to_owned())
611 ///         .expect("Unable to send on channel");
612 /// });
613 ///
614 /// let receiver = thread::spawn(move || {
615 ///     let value = rx.recv().expect("Unable to receive from channel");
616 ///     println!("{}", value);
617 /// });
618 ///
619 /// sender.join().expect("The sender thread has panicked");
620 /// receiver.join().expect("The receiver thread has panicked");
621 /// ```
622 ///
623 /// A thread can also return a value through its [`JoinHandle`], you can use
624 /// this to make asynchronous computations (futures might be more appropriate
625 /// though).
626 ///
627 /// ```
628 /// use std::thread;
629 ///
630 /// let computation = thread::spawn(|| {
631 ///     // Some expensive computation.
632 ///     42
633 /// });
634 ///
635 /// let result = computation.join().unwrap();
636 /// println!("{}", result);
637 /// ```
638 ///
639 /// [`channels`]: crate::sync::mpsc
640 /// [`join`]: JoinHandle::join
641 /// [`Err`]: crate::result::Result::Err
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn spawn<F, T>(f: F) -> JoinHandle<T>
644 where
645     F: FnOnce() -> T,
646     F: Send + 'static,
647     T: Send + 'static,
648 {
649     Builder::new().spawn(f).expect("failed to spawn thread")
650 }
651
652 /// Gets a handle to the thread that invokes it.
653 ///
654 /// # Examples
655 ///
656 /// Getting a handle to the current thread with `thread::current()`:
657 ///
658 /// ```
659 /// use std::thread;
660 ///
661 /// let handler = thread::Builder::new()
662 ///     .name("named thread".into())
663 ///     .spawn(|| {
664 ///         let handle = thread::current();
665 ///         assert_eq!(handle.name(), Some("named thread"));
666 ///     })
667 ///     .unwrap();
668 ///
669 /// handler.join().unwrap();
670 /// ```
671 #[must_use]
672 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn current() -> Thread {
674     thread_info::current_thread().expect(
675         "use of std::thread::current() is not possible \
676          after the thread's local data has been destroyed",
677     )
678 }
679
680 /// Cooperatively gives up a timeslice to the OS scheduler.
681 ///
682 /// This calls the underlying OS scheduler's yield primitive, signaling
683 /// that the calling thread is willing to give up its remaining timeslice
684 /// so that the OS may schedule other threads on the CPU.
685 ///
686 /// A drawback of yielding in a loop is that if the OS does not have any
687 /// other ready threads to run on the current CPU, the thread will effectively
688 /// busy-wait, which wastes CPU time and energy.
689 ///
690 /// Therefore, when waiting for events of interest, a programmer's first
691 /// choice should be to use synchronization devices such as [`channel`]s,
692 /// [`Condvar`]s, [`Mutex`]es or [`join`] since these primitives are
693 /// implemented in a blocking manner, giving up the CPU until the event
694 /// of interest has occurred which avoids repeated yielding.
695 ///
696 /// `yield_now` should thus be used only rarely, mostly in situations where
697 /// repeated polling is required because there is no other suitable way to
698 /// learn when an event of interest has occurred.
699 ///
700 /// # Examples
701 ///
702 /// ```
703 /// use std::thread;
704 ///
705 /// thread::yield_now();
706 /// ```
707 ///
708 /// [`channel`]: crate::sync::mpsc
709 /// [`join`]: JoinHandle::join
710 /// [`Condvar`]: crate::sync::Condvar
711 /// [`Mutex`]: crate::sync::Mutex
712 #[stable(feature = "rust1", since = "1.0.0")]
713 pub fn yield_now() {
714     imp::Thread::yield_now()
715 }
716
717 /// Determines whether the current thread is unwinding because of panic.
718 ///
719 /// A common use of this feature is to poison shared resources when writing
720 /// unsafe code, by checking `panicking` when the `drop` is called.
721 ///
722 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
723 /// already poison themselves when a thread panics while holding the lock.
724 ///
725 /// This can also be used in multithreaded applications, in order to send a
726 /// message to other threads warning that a thread has panicked (e.g., for
727 /// monitoring purposes).
728 ///
729 /// # Examples
730 ///
731 /// ```should_panic
732 /// use std::thread;
733 ///
734 /// struct SomeStruct;
735 ///
736 /// impl Drop for SomeStruct {
737 ///     fn drop(&mut self) {
738 ///         if thread::panicking() {
739 ///             println!("dropped while unwinding");
740 ///         } else {
741 ///             println!("dropped while not unwinding");
742 ///         }
743 ///     }
744 /// }
745 ///
746 /// {
747 ///     print!("a: ");
748 ///     let a = SomeStruct;
749 /// }
750 ///
751 /// {
752 ///     print!("b: ");
753 ///     let b = SomeStruct;
754 ///     panic!()
755 /// }
756 /// ```
757 ///
758 /// [Mutex]: crate::sync::Mutex
759 #[inline]
760 #[must_use]
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn panicking() -> bool {
763     panicking::panicking()
764 }
765
766 /// Puts the current thread to sleep for at least the specified amount of time.
767 ///
768 /// The thread may sleep longer than the duration specified due to scheduling
769 /// specifics or platform-dependent functionality. It will never sleep less.
770 ///
771 /// This function is blocking, and should not be used in `async` functions.
772 ///
773 /// # Platform-specific behavior
774 ///
775 /// On Unix platforms, the underlying syscall may be interrupted by a
776 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
777 /// the specified duration, this function may invoke that system call multiple
778 /// times.
779 ///
780 /// # Examples
781 ///
782 /// ```no_run
783 /// use std::thread;
784 ///
785 /// // Let's sleep for 2 seconds:
786 /// thread::sleep_ms(2000);
787 /// ```
788 #[stable(feature = "rust1", since = "1.0.0")]
789 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
790 pub fn sleep_ms(ms: u32) {
791     sleep(Duration::from_millis(ms as u64))
792 }
793
794 /// Puts the current thread to sleep for at least the specified amount of time.
795 ///
796 /// The thread may sleep longer than the duration specified due to scheduling
797 /// specifics or platform-dependent functionality. It will never sleep less.
798 ///
799 /// This function is blocking, and should not be used in `async` functions.
800 ///
801 /// # Platform-specific behavior
802 ///
803 /// On Unix platforms, the underlying syscall may be interrupted by a
804 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
805 /// the specified duration, this function may invoke that system call multiple
806 /// times.
807 /// Platforms which do not support nanosecond precision for sleeping will
808 /// have `dur` rounded up to the nearest granularity of time they can sleep for.
809 ///
810 /// Currently, specifying a zero duration on Unix platforms returns immediately
811 /// without invoking the underlying [`nanosleep`] syscall, whereas on Windows
812 /// platforms the underlying [`Sleep`] syscall is always invoked.
813 /// If the intention is to yield the current time-slice you may want to use
814 /// [`yield_now`] instead.
815 ///
816 /// [`nanosleep`]: https://linux.die.net/man/2/nanosleep
817 /// [`Sleep`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
818 ///
819 /// # Examples
820 ///
821 /// ```no_run
822 /// use std::{thread, time};
823 ///
824 /// let ten_millis = time::Duration::from_millis(10);
825 /// let now = time::Instant::now();
826 ///
827 /// thread::sleep(ten_millis);
828 ///
829 /// assert!(now.elapsed() >= ten_millis);
830 /// ```
831 #[stable(feature = "thread_sleep", since = "1.4.0")]
832 pub fn sleep(dur: Duration) {
833     imp::Thread::sleep(dur)
834 }
835
836 /// Blocks unless or until the current thread's token is made available.
837 ///
838 /// A call to `park` does not guarantee that the thread will remain parked
839 /// forever, and callers should be prepared for this possibility.
840 ///
841 /// # park and unpark
842 ///
843 /// Every thread is equipped with some basic low-level blocking support, via the
844 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
845 /// method. [`park`] blocks the current thread, which can then be resumed from
846 /// another thread by calling the [`unpark`] method on the blocked thread's
847 /// handle.
848 ///
849 /// Conceptually, each [`Thread`] handle has an associated token, which is
850 /// initially not present:
851 ///
852 /// * The [`thread::park`][`park`] function blocks the current thread unless or
853 ///   until the token is available for its thread handle, at which point it
854 ///   atomically consumes the token. It may also return *spuriously*, without
855 ///   consuming the token. [`thread::park_timeout`] does the same, but allows
856 ///   specifying a maximum time to block the thread for.
857 ///
858 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
859 ///   if it wasn't already. Because the token is initially absent, [`unpark`]
860 ///   followed by [`park`] will result in the second call returning immediately.
861 ///
862 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
863 /// locked and unlocked using `park` and `unpark`.
864 ///
865 /// Notice that being unblocked does not imply any synchronization with someone
866 /// that unparked this thread, it could also be spurious.
867 /// For example, it would be a valid, but inefficient, implementation to make both [`park`] and
868 /// [`unpark`] return immediately without doing anything.
869 ///
870 /// The API is typically used by acquiring a handle to the current thread,
871 /// placing that handle in a shared data structure so that other threads can
872 /// find it, and then `park`ing in a loop. When some desired condition is met, another
873 /// thread calls [`unpark`] on the handle.
874 ///
875 /// The motivation for this design is twofold:
876 ///
877 /// * It avoids the need to allocate mutexes and condvars when building new
878 ///   synchronization primitives; the threads already provide basic
879 ///   blocking/signaling.
880 ///
881 /// * It can be implemented very efficiently on many platforms.
882 ///
883 /// # Examples
884 ///
885 /// ```
886 /// use std::thread;
887 /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
888 /// use std::time::Duration;
889 ///
890 /// let flag = Arc::new(AtomicBool::new(false));
891 /// let flag2 = Arc::clone(&flag);
892 ///
893 /// let parked_thread = thread::spawn(move || {
894 ///     // We want to wait until the flag is set. We *could* just spin, but using
895 ///     // park/unpark is more efficient.
896 ///     while !flag2.load(Ordering::Acquire) {
897 ///         println!("Parking thread");
898 ///         thread::park();
899 ///         // We *could* get here spuriously, i.e., way before the 10ms below are over!
900 ///         // But that is no problem, we are in a loop until the flag is set anyway.
901 ///         println!("Thread unparked");
902 ///     }
903 ///     println!("Flag received");
904 /// });
905 ///
906 /// // Let some time pass for the thread to be spawned.
907 /// thread::sleep(Duration::from_millis(10));
908 ///
909 /// // Set the flag, and let the thread wake up.
910 /// // There is no race condition here, if `unpark`
911 /// // happens first, `park` will return immediately.
912 /// // Hence there is no risk of a deadlock.
913 /// flag.store(true, Ordering::Release);
914 /// println!("Unpark the thread");
915 /// parked_thread.thread().unpark();
916 ///
917 /// parked_thread.join().unwrap();
918 /// ```
919 ///
920 /// [`unpark`]: Thread::unpark
921 /// [`thread::park_timeout`]: park_timeout
922 #[stable(feature = "rust1", since = "1.0.0")]
923 pub fn park() {
924     // SAFETY: park_timeout is called on the parker owned by this thread.
925     unsafe {
926         current().inner.parker.park();
927     }
928 }
929
930 /// Use [`park_timeout`].
931 ///
932 /// Blocks unless or until the current thread's token is made available or
933 /// the specified duration has been reached (may wake spuriously).
934 ///
935 /// The semantics of this function are equivalent to [`park`] except
936 /// that the thread will be blocked for roughly no longer than `dur`. This
937 /// method should not be used for precise timing due to anomalies such as
938 /// preemption or platform differences that might not cause the maximum
939 /// amount of time waited to be precisely `ms` long.
940 ///
941 /// See the [park documentation][`park`] for more detail.
942 #[stable(feature = "rust1", since = "1.0.0")]
943 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
944 pub fn park_timeout_ms(ms: u32) {
945     park_timeout(Duration::from_millis(ms as u64))
946 }
947
948 /// Blocks unless or until the current thread's token is made available or
949 /// the specified duration has been reached (may wake spuriously).
950 ///
951 /// The semantics of this function are equivalent to [`park`][park] except
952 /// that the thread will be blocked for roughly no longer than `dur`. This
953 /// method should not be used for precise timing due to anomalies such as
954 /// preemption or platform differences that might not cause the maximum
955 /// amount of time waited to be precisely `dur` long.
956 ///
957 /// See the [park documentation][park] for more details.
958 ///
959 /// # Platform-specific behavior
960 ///
961 /// Platforms which do not support nanosecond precision for sleeping will have
962 /// `dur` rounded up to the nearest granularity of time they can sleep for.
963 ///
964 /// # Examples
965 ///
966 /// Waiting for the complete expiration of the timeout:
967 ///
968 /// ```rust,no_run
969 /// use std::thread::park_timeout;
970 /// use std::time::{Instant, Duration};
971 ///
972 /// let timeout = Duration::from_secs(2);
973 /// let beginning_park = Instant::now();
974 ///
975 /// let mut timeout_remaining = timeout;
976 /// loop {
977 ///     park_timeout(timeout_remaining);
978 ///     let elapsed = beginning_park.elapsed();
979 ///     if elapsed >= timeout {
980 ///         break;
981 ///     }
982 ///     println!("restarting park_timeout after {:?}", elapsed);
983 ///     timeout_remaining = timeout - elapsed;
984 /// }
985 /// ```
986 #[stable(feature = "park_timeout", since = "1.4.0")]
987 pub fn park_timeout(dur: Duration) {
988     // SAFETY: park_timeout is called on the parker owned by this thread.
989     unsafe {
990         current().inner.parker.park_timeout(dur);
991     }
992 }
993
994 ////////////////////////////////////////////////////////////////////////////////
995 // ThreadId
996 ////////////////////////////////////////////////////////////////////////////////
997
998 /// A unique identifier for a running thread.
999 ///
1000 /// A `ThreadId` is an opaque object that uniquely identifies each thread
1001 /// created during the lifetime of a process. `ThreadId`s are guaranteed not to
1002 /// be reused, even when a thread terminates. `ThreadId`s are under the control
1003 /// of Rust's standard library and there may not be any relationship between
1004 /// `ThreadId` and the underlying platform's notion of a thread identifier --
1005 /// the two concepts cannot, therefore, be used interchangeably. A `ThreadId`
1006 /// can be retrieved from the [`id`] method on a [`Thread`].
1007 ///
1008 /// # Examples
1009 ///
1010 /// ```
1011 /// use std::thread;
1012 ///
1013 /// let other_thread = thread::spawn(|| {
1014 ///     thread::current().id()
1015 /// });
1016 ///
1017 /// let other_thread_id = other_thread.join().unwrap();
1018 /// assert!(thread::current().id() != other_thread_id);
1019 /// ```
1020 ///
1021 /// [`id`]: Thread::id
1022 #[stable(feature = "thread_id", since = "1.19.0")]
1023 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1024 pub struct ThreadId(NonZeroU64);
1025
1026 impl ThreadId {
1027     // Generate a new unique thread ID.
1028     fn new() -> ThreadId {
1029         // It is UB to attempt to acquire this mutex reentrantly!
1030         static GUARD: mutex::StaticMutex = mutex::StaticMutex::new();
1031         static mut COUNTER: u64 = 1;
1032
1033         unsafe {
1034             let guard = GUARD.lock();
1035
1036             // If we somehow use up all our bits, panic so that we're not
1037             // covering up subtle bugs of IDs being reused.
1038             if COUNTER == u64::MAX {
1039                 drop(guard); // in case the panic handler ends up calling `ThreadId::new()`, avoid reentrant lock acquire.
1040                 panic!("failed to generate unique thread ID: bitspace exhausted");
1041             }
1042
1043             let id = COUNTER;
1044             COUNTER += 1;
1045
1046             ThreadId(NonZeroU64::new(id).unwrap())
1047         }
1048     }
1049
1050     /// This returns a numeric identifier for the thread identified by this
1051     /// `ThreadId`.
1052     ///
1053     /// As noted in the documentation for the type itself, it is essentially an
1054     /// opaque ID, but is guaranteed to be unique for each thread. The returned
1055     /// value is entirely opaque -- only equality testing is stable. Note that
1056     /// it is not guaranteed which values new threads will return, and this may
1057     /// change across Rust versions.
1058     #[must_use]
1059     #[unstable(feature = "thread_id_value", issue = "67939")]
1060     pub fn as_u64(&self) -> NonZeroU64 {
1061         self.0
1062     }
1063 }
1064
1065 ////////////////////////////////////////////////////////////////////////////////
1066 // Thread
1067 ////////////////////////////////////////////////////////////////////////////////
1068
1069 /// The internal representation of a `Thread` handle
1070 struct Inner {
1071     name: Option<CString>, // Guaranteed to be UTF-8
1072     id: ThreadId,
1073     parker: Parker,
1074 }
1075
1076 #[derive(Clone)]
1077 #[stable(feature = "rust1", since = "1.0.0")]
1078 /// A handle to a thread.
1079 ///
1080 /// Threads are represented via the `Thread` type, which you can get in one of
1081 /// two ways:
1082 ///
1083 /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1084 ///   function, and calling [`thread`][`JoinHandle::thread`] on the
1085 ///   [`JoinHandle`].
1086 /// * By requesting the current thread, using the [`thread::current`] function.
1087 ///
1088 /// The [`thread::current`] function is available even for threads not spawned
1089 /// by the APIs of this module.
1090 ///
1091 /// There is usually no need to create a `Thread` struct yourself, one
1092 /// should instead use a function like `spawn` to create new threads, see the
1093 /// docs of [`Builder`] and [`spawn`] for more details.
1094 ///
1095 /// [`thread::current`]: current
1096 pub struct Thread {
1097     inner: Arc<Inner>,
1098 }
1099
1100 impl Thread {
1101     // Used only internally to construct a thread object without spawning
1102     // Panics if the name contains nuls.
1103     pub(crate) fn new(name: Option<CString>) -> Thread {
1104         Thread { inner: Arc::new(Inner { name, id: ThreadId::new(), parker: Parker::new() }) }
1105     }
1106
1107     /// Atomically makes the handle's token available if it is not already.
1108     ///
1109     /// Every thread is equipped with some basic low-level blocking support, via
1110     /// the [`park`][park] function and the `unpark()` method. These can be
1111     /// used as a more CPU-efficient implementation of a spinlock.
1112     ///
1113     /// See the [park documentation][park] for more details.
1114     ///
1115     /// # Examples
1116     ///
1117     /// ```
1118     /// use std::thread;
1119     /// use std::time::Duration;
1120     ///
1121     /// let parked_thread = thread::Builder::new()
1122     ///     .spawn(|| {
1123     ///         println!("Parking thread");
1124     ///         thread::park();
1125     ///         println!("Thread unparked");
1126     ///     })
1127     ///     .unwrap();
1128     ///
1129     /// // Let some time pass for the thread to be spawned.
1130     /// thread::sleep(Duration::from_millis(10));
1131     ///
1132     /// println!("Unpark the thread");
1133     /// parked_thread.thread().unpark();
1134     ///
1135     /// parked_thread.join().unwrap();
1136     /// ```
1137     #[stable(feature = "rust1", since = "1.0.0")]
1138     #[inline]
1139     pub fn unpark(&self) {
1140         self.inner.parker.unpark();
1141     }
1142
1143     /// Gets the thread's unique identifier.
1144     ///
1145     /// # Examples
1146     ///
1147     /// ```
1148     /// use std::thread;
1149     ///
1150     /// let other_thread = thread::spawn(|| {
1151     ///     thread::current().id()
1152     /// });
1153     ///
1154     /// let other_thread_id = other_thread.join().unwrap();
1155     /// assert!(thread::current().id() != other_thread_id);
1156     /// ```
1157     #[stable(feature = "thread_id", since = "1.19.0")]
1158     #[must_use]
1159     pub fn id(&self) -> ThreadId {
1160         self.inner.id
1161     }
1162
1163     /// Gets the thread's name.
1164     ///
1165     /// For more information about named threads, see
1166     /// [this module-level documentation][naming-threads].
1167     ///
1168     /// # Examples
1169     ///
1170     /// Threads by default have no name specified:
1171     ///
1172     /// ```
1173     /// use std::thread;
1174     ///
1175     /// let builder = thread::Builder::new();
1176     ///
1177     /// let handler = builder.spawn(|| {
1178     ///     assert!(thread::current().name().is_none());
1179     /// }).unwrap();
1180     ///
1181     /// handler.join().unwrap();
1182     /// ```
1183     ///
1184     /// Thread with a specified name:
1185     ///
1186     /// ```
1187     /// use std::thread;
1188     ///
1189     /// let builder = thread::Builder::new()
1190     ///     .name("foo".into());
1191     ///
1192     /// let handler = builder.spawn(|| {
1193     ///     assert_eq!(thread::current().name(), Some("foo"))
1194     /// }).unwrap();
1195     ///
1196     /// handler.join().unwrap();
1197     /// ```
1198     ///
1199     /// [naming-threads]: ./index.html#naming-threads
1200     #[stable(feature = "rust1", since = "1.0.0")]
1201     #[must_use]
1202     pub fn name(&self) -> Option<&str> {
1203         self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
1204     }
1205
1206     fn cname(&self) -> Option<&CStr> {
1207         self.inner.name.as_deref()
1208     }
1209 }
1210
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 impl fmt::Debug for Thread {
1213     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1214         f.debug_struct("Thread")
1215             .field("id", &self.id())
1216             .field("name", &self.name())
1217             .finish_non_exhaustive()
1218     }
1219 }
1220
1221 ////////////////////////////////////////////////////////////////////////////////
1222 // JoinHandle
1223 ////////////////////////////////////////////////////////////////////////////////
1224
1225 /// A specialized [`Result`] type for threads.
1226 ///
1227 /// Indicates the manner in which a thread exited.
1228 ///
1229 /// The value contained in the `Result::Err` variant
1230 /// is the value the thread panicked with;
1231 /// that is, the argument the `panic!` macro was called with.
1232 /// Unlike with normal errors, this value doesn't implement
1233 /// the [`Error`](crate::error::Error) trait.
1234 ///
1235 /// Thus, a sensible way to handle a thread panic is to either:
1236 ///
1237 /// 1. propagate the panic with [`std::panic::resume_unwind`]
1238 /// 2. or in case the thread is intended to be a subsystem boundary
1239 /// that is supposed to isolate system-level failures,
1240 /// match on the `Err` variant and handle the panic in an appropriate way
1241 ///
1242 /// A thread that completes without panicking is considered to exit successfully.
1243 ///
1244 /// # Examples
1245 ///
1246 /// Matching on the result of a joined thread:
1247 ///
1248 /// ```no_run
1249 /// use std::{fs, thread, panic};
1250 ///
1251 /// fn copy_in_thread() -> thread::Result<()> {
1252 ///     thread::spawn(|| {
1253 ///         fs::copy("foo.txt", "bar.txt").unwrap();
1254 ///     }).join()
1255 /// }
1256 ///
1257 /// fn main() {
1258 ///     match copy_in_thread() {
1259 ///         Ok(_) => println!("copy succeeded"),
1260 ///         Err(e) => panic::resume_unwind(e),
1261 ///     }
1262 /// }
1263 /// ```
1264 ///
1265 /// [`Result`]: crate::result::Result
1266 /// [`std::panic::resume_unwind`]: crate::panic::resume_unwind
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
1269
1270 // This packet is used to communicate the return value between the spawned
1271 // thread and the rest of the program. It is shared through an `Arc` and
1272 // there's no need for a mutex here because synchronization happens with `join()`
1273 // (the caller will never read this packet until the thread has exited).
1274 //
1275 // An Arc to the packet is stored into a `JoinInner` which in turns is placed
1276 // in `JoinHandle`.
1277 struct Packet<'scope, T> {
1278     scope: Option<&'scope scoped::ScopeData>,
1279     result: UnsafeCell<Option<Result<T>>>,
1280 }
1281
1282 // Due to the usage of `UnsafeCell` we need to manually implement Sync.
1283 // The type `T` should already always be Send (otherwise the thread could not
1284 // have been created) and the Packet is Sync because all access to the
1285 // `UnsafeCell` synchronized (by the `join()` boundary), and `ScopeData` is Sync.
1286 unsafe impl<'scope, T: Sync> Sync for Packet<'scope, T> {}
1287
1288 impl<'scope, T> Drop for Packet<'scope, T> {
1289     fn drop(&mut self) {
1290         // Book-keeping so the scope knows when it's done.
1291         if let Some(scope) = self.scope {
1292             // If this packet was for a thread that ran in a scope, the thread
1293             // panicked, and nobody consumed the panic payload, we make sure
1294             // the scope function will panic.
1295             let unhandled_panic = matches!(self.result.get_mut(), Some(Err(_)));
1296             // Drop the result before decrementing the number of running
1297             // threads, because the Drop implementation might still use things
1298             // it borrowed from 'scope.
1299             // This is only relevant for threads that aren't join()ed, as
1300             // join() will take the `result` and set it to None, such that
1301             // there is nothing left to drop here.
1302             // If this drop panics, that just results in an abort, because
1303             // we're outside of the outermost `catch_unwind` of our thread.
1304             // The same happens for detached non-scoped threads when dropping
1305             // their ignored return value (or panic payload) panics, so
1306             // there's no need to try to do anything better.
1307             // (And even if we tried to handle it, we'd also need to handle
1308             // the case where the panic payload we get out of it also panics
1309             // on drop, and so on. See issue #86027.)
1310             *self.result.get_mut() = None;
1311             // Now that there will be no more user code running on this thread
1312             // that can use 'scope, mark the thread as 'finished'.
1313             scope.decrement_num_running_threads(unhandled_panic);
1314         }
1315     }
1316 }
1317
1318 /// Inner representation for JoinHandle
1319 struct JoinInner<'scope, T> {
1320     native: imp::Thread,
1321     thread: Thread,
1322     packet: Arc<Packet<'scope, T>>,
1323 }
1324
1325 impl<'scope, T> JoinInner<'scope, T> {
1326     fn join(mut self) -> Result<T> {
1327         self.native.join();
1328         Arc::get_mut(&mut self.packet).unwrap().result.get_mut().take().unwrap()
1329     }
1330 }
1331
1332 /// An owned permission to join on a thread (block on its termination).
1333 ///
1334 /// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1335 /// means that there is no longer any handle to the thread and no way to `join`
1336 /// on it.
1337 ///
1338 /// Due to platform restrictions, it is not possible to [`Clone`] this
1339 /// handle: the ability to join a thread is a uniquely-owned permission.
1340 ///
1341 /// This `struct` is created by the [`thread::spawn`] function and the
1342 /// [`thread::Builder::spawn`] method.
1343 ///
1344 /// # Examples
1345 ///
1346 /// Creation from [`thread::spawn`]:
1347 ///
1348 /// ```
1349 /// use std::thread;
1350 ///
1351 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1352 ///     // some work here
1353 /// });
1354 /// ```
1355 ///
1356 /// Creation from [`thread::Builder::spawn`]:
1357 ///
1358 /// ```
1359 /// use std::thread;
1360 ///
1361 /// let builder = thread::Builder::new();
1362 ///
1363 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1364 ///     // some work here
1365 /// }).unwrap();
1366 /// ```
1367 ///
1368 /// A thread being detached and outliving the thread that spawned it:
1369 ///
1370 /// ```no_run
1371 /// use std::thread;
1372 /// use std::time::Duration;
1373 ///
1374 /// let original_thread = thread::spawn(|| {
1375 ///     let _detached_thread = thread::spawn(|| {
1376 ///         // Here we sleep to make sure that the first thread returns before.
1377 ///         thread::sleep(Duration::from_millis(10));
1378 ///         // This will be called, even though the JoinHandle is dropped.
1379 ///         println!("♫ Still alive ♫");
1380 ///     });
1381 /// });
1382 ///
1383 /// original_thread.join().expect("The thread being joined has panicked");
1384 /// println!("Original thread is joined.");
1385 ///
1386 /// // We make sure that the new thread has time to run, before the main
1387 /// // thread returns.
1388 ///
1389 /// thread::sleep(Duration::from_millis(1000));
1390 /// ```
1391 ///
1392 /// [`thread::Builder::spawn`]: Builder::spawn
1393 /// [`thread::spawn`]: spawn
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 pub struct JoinHandle<T>(JoinInner<'static, T>);
1396
1397 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1398 unsafe impl<T> Send for JoinHandle<T> {}
1399 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1400 unsafe impl<T> Sync for JoinHandle<T> {}
1401
1402 impl<T> JoinHandle<T> {
1403     /// Extracts a handle to the underlying thread.
1404     ///
1405     /// # Examples
1406     ///
1407     /// ```
1408     /// use std::thread;
1409     ///
1410     /// let builder = thread::Builder::new();
1411     ///
1412     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1413     ///     // some work here
1414     /// }).unwrap();
1415     ///
1416     /// let thread = join_handle.thread();
1417     /// println!("thread id: {:?}", thread.id());
1418     /// ```
1419     #[stable(feature = "rust1", since = "1.0.0")]
1420     #[must_use]
1421     pub fn thread(&self) -> &Thread {
1422         &self.0.thread
1423     }
1424
1425     /// Waits for the associated thread to finish.
1426     ///
1427     /// This function will return immediately if the associated thread has already finished.
1428     ///
1429     /// In terms of [atomic memory orderings],  the completion of the associated
1430     /// thread synchronizes with this function returning. In other words, all
1431     /// operations performed by that thread [happen
1432     /// before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) all
1433     /// operations that happen after `join` returns.
1434     ///
1435     /// If the associated thread panics, [`Err`] is returned with the parameter given
1436     /// to [`panic!`].
1437     ///
1438     /// [`Err`]: crate::result::Result::Err
1439     /// [atomic memory orderings]: crate::sync::atomic
1440     ///
1441     /// # Panics
1442     ///
1443     /// This function may panic on some platforms if a thread attempts to join
1444     /// itself or otherwise may create a deadlock with joining threads.
1445     ///
1446     /// # Examples
1447     ///
1448     /// ```
1449     /// use std::thread;
1450     ///
1451     /// let builder = thread::Builder::new();
1452     ///
1453     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1454     ///     // some work here
1455     /// }).unwrap();
1456     /// join_handle.join().expect("Couldn't join on the associated thread");
1457     /// ```
1458     #[stable(feature = "rust1", since = "1.0.0")]
1459     pub fn join(self) -> Result<T> {
1460         self.0.join()
1461     }
1462
1463     /// Checks if the associated thread has finished running its main function.
1464     ///
1465     /// This might return `true` for a brief moment after the thread's main
1466     /// function has returned, but before the thread itself has stopped running.
1467     /// However, once this returns `true`, [`join`][Self::join] can be expected
1468     /// to return quickly, without blocking for any significant amount of time.
1469     ///
1470     /// This function does not block. To block while waiting on the thread to finish,
1471     /// use [`join`][Self::join].
1472     #[unstable(feature = "thread_is_running", issue = "90470")]
1473     pub fn is_finished(&self) -> bool {
1474         Arc::strong_count(&self.0.packet) == 1
1475     }
1476 }
1477
1478 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1479     fn as_inner(&self) -> &imp::Thread {
1480         &self.0.native
1481     }
1482 }
1483
1484 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1485     fn into_inner(self) -> imp::Thread {
1486         self.0.native
1487     }
1488 }
1489
1490 #[stable(feature = "std_debug", since = "1.16.0")]
1491 impl<T> fmt::Debug for JoinHandle<T> {
1492     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1493         f.debug_struct("JoinHandle").finish_non_exhaustive()
1494     }
1495 }
1496
1497 fn _assert_sync_and_send() {
1498     fn _assert_both<T: Send + Sync>() {}
1499     _assert_both::<JoinHandle<()>>();
1500     _assert_both::<Thread>();
1501 }
1502
1503 /// Returns an estimate of the default amount of parallelism a program should use.
1504 ///
1505 /// Parallelism is a resource. A given machine provides a certain capacity for
1506 /// parallelism, i.e., a bound on the number of computations it can perform
1507 /// simultaneously. This number often corresponds to the amount of CPUs a
1508 /// computer has, but it may diverge in various cases.
1509 ///
1510 /// Host environments such as VMs or container orchestrators may want to
1511 /// restrict the amount of parallelism made available to programs in them. This
1512 /// is often done to limit the potential impact of (unintentionally)
1513 /// resource-intensive programs on other programs running on the same machine.
1514 ///
1515 /// # Limitations
1516 ///
1517 /// The purpose of this API is to provide an easy and portable way to query
1518 /// the default amount of parallelism the program should use. Among other things it
1519 /// does not expose information on NUMA regions, does not account for
1520 /// differences in (co)processor capabilities or current system load,
1521 /// and will not modify the program's global state in order to more accurately
1522 /// query the amount of available parallelism.
1523 ///
1524 /// Where both fixed steady-state and burst limits are available the steady-state
1525 /// capacity will be used to ensure more predictable latencies.
1526 ///
1527 /// Resource limits can be changed during the runtime of a program, therefore the value is
1528 /// not cached and instead recomputed every time this function is called. It should not be
1529 /// called from hot code.
1530 ///
1531 /// The value returned by this function should be considered a simplified
1532 /// approximation of the actual amount of parallelism available at any given
1533 /// time. To get a more detailed or precise overview of the amount of
1534 /// parallelism available to the program, you may wish to use
1535 /// platform-specific APIs as well. The following platform limitations currently
1536 /// apply to `available_parallelism`:
1537 ///
1538 /// On Windows:
1539 /// - It may undercount the amount of parallelism available on systems with more
1540 ///   than 64 logical CPUs. However, programs typically need specific support to
1541 ///   take advantage of more than 64 logical CPUs, and in the absence of such
1542 ///   support, the number returned by this function accurately reflects the
1543 ///   number of logical CPUs the program can use by default.
1544 /// - It may overcount the amount of parallelism available on systems limited by
1545 ///   process-wide affinity masks, or job object limitations.
1546 ///
1547 /// On Linux:
1548 /// - It may overcount the amount of parallelism available when limited by a
1549 ///   process-wide affinity mask or cgroup quotas and cgroup2 fs or `sched_getaffinity()` can't be
1550 ///   queried, e.g. due to sandboxing.
1551 /// - It may undercount the amount of parallelism if the current thread's affinity mask
1552 ///   does not reflect the process' cpuset, e.g. due to pinned threads.
1553 ///
1554 /// On all targets:
1555 /// - It may overcount the amount of parallelism available when running in a VM
1556 /// with CPU usage limits (e.g. an overcommitted host).
1557 ///
1558 /// # Errors
1559 ///
1560 /// This function will, but is not limited to, return errors in the following
1561 /// cases:
1562 ///
1563 /// - If the amount of parallelism is not known for the target platform.
1564 /// - If the program lacks permission to query the amount of parallelism made
1565 ///   available to it.
1566 ///
1567 /// # Examples
1568 ///
1569 /// ```
1570 /// # #![allow(dead_code)]
1571 /// use std::{io, thread};
1572 ///
1573 /// fn main() -> io::Result<()> {
1574 ///     let count = thread::available_parallelism()?.get();
1575 ///     assert!(count >= 1_usize);
1576 ///     Ok(())
1577 /// }
1578 /// ```
1579 #[doc(alias = "available_concurrency")] // Alias for a previous name we gave this API on unstable.
1580 #[doc(alias = "hardware_concurrency")] // Alias for C++ `std::thread::hardware_concurrency`.
1581 #[doc(alias = "num_cpus")] // Alias for a popular ecosystem crate which provides similar functionality.
1582 #[stable(feature = "available_parallelism", since = "1.59.0")]
1583 pub fn available_parallelism() -> io::Result<NonZeroUsize> {
1584     imp::available_parallelism()
1585 }