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