3 //! ## The threading model
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.
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`].
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.
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).
33 //! ## Spawning a thread
35 //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
40 //! thread::spawn(move || {
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
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
57 //! let thread_join_handle = thread::spawn(move || {
61 //! let res = thread_join_handle.join();
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.
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.
72 //! ## Configuring threads
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:
78 //! # #![allow(unused_must_use)]
81 //! thread::Builder::new().name("thread1".to_string()).spawn(move || {
82 //! println!("Hello, world!");
86 //! ## The `Thread` type
88 //! Threads are represented via the [`Thread`] type, which you can get in one of
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.
95 //! The [`thread::current`] function is available even for threads not spawned
96 //! by the APIs of this module.
98 //! ## Thread-local storage
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.
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.
114 //! ## Naming threads
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:
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).
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
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.
135 //! Note that the stack size of the main thread is *not* determined by Rust.
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
151 #![stable(feature = "rust1", since = "1.0.0")]
152 #![deny(unsafe_op_in_unsafe_fn)]
154 #[cfg(all(test, not(target_os = "emscripten")))]
158 use crate::cell::UnsafeCell;
159 use crate::ffi::{CStr, CString};
163 use crate::num::NonZeroU64;
164 use crate::num::NonZeroUsize;
166 use crate::panicking;
168 use crate::ptr::addr_of_mut;
170 use crate::sync::Arc;
171 use crate::sys::thread as imp;
172 use crate::sys_common::mutex;
173 use crate::sys_common::thread;
174 use crate::sys_common::thread_info;
175 use crate::sys_common::thread_parker::Parker;
176 use crate::sys_common::{AsInner, IntoInner};
177 use crate::time::Duration;
179 ////////////////////////////////////////////////////////////////////////////////
180 // Thread-local storage
181 ////////////////////////////////////////////////////////////////////////////////
186 #[unstable(feature = "scoped_threads", issue = "93203")]
189 #[unstable(feature = "scoped_threads", issue = "93203")]
190 pub use scoped::{scope, Scope, ScopedJoinHandle};
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub use self::local::{AccessError, LocalKey};
195 // The types used by the thread_local! macro to access TLS keys. Note that there
196 // are two types, the "OS" type and the "fast" type. The OS thread local key
197 // type is accessed via platform-specific API calls and is slow, while the fast
198 // key type is accessed via code generated via LLVM, where TLS keys are set up
199 // by the elf linker. Note that the OS TLS type is always available: on macOS
200 // the standard library is compiled with support for older platform versions
201 // where fast TLS was not available; end-user code is compiled with fast TLS
202 // where available, but both are needed.
204 #[unstable(feature = "libstd_thread_internals", issue = "none")]
205 #[cfg(target_thread_local)]
207 pub use self::local::fast::Key as __FastLocalKeyInner;
208 #[unstable(feature = "libstd_thread_internals", issue = "none")]
210 pub use self::local::os::Key as __OsLocalKeyInner;
211 #[unstable(feature = "libstd_thread_internals", issue = "none")]
212 #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
214 pub use self::local::statik::Key as __StaticLocalKeyInner;
216 ////////////////////////////////////////////////////////////////////////////////
218 ////////////////////////////////////////////////////////////////////////////////
220 /// Thread factory, which can be used in order to configure the properties of
223 /// Methods can be chained on it in order to configure it.
225 /// The two configurations available are:
227 /// - [`name`]: specifies an [associated name for the thread][naming-threads]
228 /// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
230 /// The [`spawn`] method will take ownership of the builder and create an
231 /// [`io::Result`] to the thread handle with the given configuration.
233 /// The [`thread::spawn`] free function uses a `Builder` with default
234 /// configuration and [`unwrap`]s its return value.
236 /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
237 /// to recover from a failure to launch a thread, indeed the free function will
238 /// panic where the `Builder` method will return a [`io::Result`].
245 /// let builder = thread::Builder::new();
247 /// let handler = builder.spawn(|| {
251 /// handler.join().unwrap();
254 /// [`stack_size`]: Builder::stack_size
255 /// [`name`]: Builder::name
256 /// [`spawn`]: Builder::spawn
257 /// [`thread::spawn`]: spawn
258 /// [`io::Result`]: crate::io::Result
259 /// [`unwrap`]: crate::result::Result::unwrap
260 /// [naming-threads]: ./index.html#naming-threads
261 /// [stack-size]: ./index.html#stack-size
262 #[must_use = "must eventually spawn the thread"]
263 #[stable(feature = "rust1", since = "1.0.0")]
266 // A name for the thread-to-be, for identification in panic messages
267 name: Option<String>,
268 // The size of the stack for the spawned thread in bytes
269 stack_size: Option<usize>,
273 /// Generates the base configuration for spawning a thread, from which
274 /// configuration methods can be chained.
281 /// let builder = thread::Builder::new()
282 /// .name("foo".into())
283 /// .stack_size(32 * 1024);
285 /// let handler = builder.spawn(|| {
289 /// handler.join().unwrap();
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub fn new() -> Builder {
293 Builder { name: None, stack_size: None }
296 /// Names the thread-to-be. Currently the name is used for identification
297 /// only in panic messages.
299 /// The name must not contain null bytes (`\0`).
301 /// For more information about named threads, see
302 /// [this module-level documentation][naming-threads].
309 /// let builder = thread::Builder::new()
310 /// .name("foo".into());
312 /// let handler = builder.spawn(|| {
313 /// assert_eq!(thread::current().name(), Some("foo"))
316 /// handler.join().unwrap();
319 /// [naming-threads]: ./index.html#naming-threads
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn name(mut self, name: String) -> Builder {
322 self.name = Some(name);
326 /// Sets the size of the stack (in bytes) for the new thread.
328 /// The actual stack size may be greater than this value if
329 /// the platform specifies a minimal stack size.
331 /// For more information about the stack size for threads, see
332 /// [this module-level documentation][stack-size].
339 /// let builder = thread::Builder::new().stack_size(32 * 1024);
342 /// [stack-size]: ./index.html#stack-size
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn stack_size(mut self, size: usize) -> Builder {
345 self.stack_size = Some(size);
349 /// Spawns a new thread by taking ownership of the `Builder`, and returns an
350 /// [`io::Result`] to its [`JoinHandle`].
352 /// The spawned thread may outlive the caller (unless the caller thread
353 /// is the main thread; the whole process is terminated when the main
354 /// thread finishes). The join handle can be used to block on
355 /// termination of the spawned thread, including recovering its panics.
357 /// For a more complete documentation see [`thread::spawn`][`spawn`].
361 /// Unlike the [`spawn`] free function, this method yields an
362 /// [`io::Result`] to capture any failure to create the thread at
365 /// [`io::Result`]: crate::io::Result
369 /// Panics if a thread name was set and it contained null bytes.
376 /// let builder = thread::Builder::new();
378 /// let handler = builder.spawn(|| {
382 /// handler.join().unwrap();
384 #[stable(feature = "rust1", since = "1.0.0")]
385 pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
391 unsafe { self.spawn_unchecked(f) }
394 /// Spawns a new thread without any lifetime restrictions by taking ownership
395 /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
397 /// The spawned thread may outlive the caller (unless the caller thread
398 /// is the main thread; the whole process is terminated when the main
399 /// thread finishes). The join handle can be used to block on
400 /// termination of the spawned thread, including recovering its panics.
402 /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
403 /// except for the relaxed lifetime bounds, which render it unsafe.
404 /// For a more complete documentation see [`thread::spawn`][`spawn`].
408 /// Unlike the [`spawn`] free function, this method yields an
409 /// [`io::Result`] to capture any failure to create the thread at
414 /// Panics if a thread name was set and it contained null bytes.
418 /// The caller has to ensure that the spawned thread does not outlive any
419 /// references in the supplied thread closure and its return type.
420 /// This can be guaranteed in two ways:
422 /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
424 /// - use only types with `'static` lifetime bounds, i.e., those with no or only
425 /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
426 /// and [`thread::spawn`][`spawn`] enforce this property statically)
431 /// #![feature(thread_spawn_unchecked)]
434 /// let builder = thread::Builder::new();
437 /// let thread_x = &x;
439 /// let handler = unsafe {
440 /// builder.spawn_unchecked(move || {
441 /// println!("x = {}", *thread_x);
445 /// // caller has to ensure `join()` is called, otherwise
446 /// // it is possible to access freed memory if `x` gets
447 /// // dropped before the thread closure is executed!
448 /// handler.join().unwrap();
451 /// [`io::Result`]: crate::io::Result
452 #[unstable(feature = "thread_spawn_unchecked", issue = "55132")]
453 pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>>
459 Ok(JoinHandle(unsafe { self.spawn_unchecked_(f, None) }?))
462 unsafe fn spawn_unchecked_<'a, 'scope, F, T>(
465 scope_data: Option<&'scope scoped::ScopeData>,
466 ) -> io::Result<JoinInner<'scope, T>>
473 let Builder { name, stack_size } = self;
475 let stack_size = stack_size.unwrap_or_else(thread::min_stack);
477 let my_thread = Thread::new(name.map(|name| {
478 CString::new(name).expect("thread name may not contain interior null bytes")
480 let their_thread = my_thread.clone();
482 let my_packet: Arc<Packet<'scope, T>> =
483 Arc::new(Packet { scope: scope_data, result: UnsafeCell::new(None) });
484 let their_packet = my_packet.clone();
486 let output_capture = crate::io::set_output_capture(None);
487 crate::io::set_output_capture(output_capture.clone());
490 if let Some(name) = their_thread.cname() {
491 imp::Thread::set_name(name);
494 crate::io::set_output_capture(output_capture);
496 // SAFETY: the stack guard passed is the one for the current thread.
497 // This means the current thread's stack and the new thread's stack
498 // are properly set and protected from each other.
499 thread_info::set(unsafe { imp::guard::current() }, their_thread);
500 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
501 crate::sys_common::backtrace::__rust_begin_short_backtrace(f)
503 // SAFETY: `their_packet` as been built just above and moved by the
504 // closure (it is an Arc<...>) and `my_packet` will be stored in the
505 // same `JoinInner` as this closure meaning the mutation will be
506 // safe (not modify it and affect a value far away).
507 unsafe { *their_packet.result.get() = Some(try_result) };
510 if let Some(scope_data) = scope_data {
511 scope_data.increment_num_running_threads();
517 // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
518 // through FFI or otherwise used with low-level threading primitives that have no
519 // notion of or way to enforce lifetimes.
521 // As mentioned in the `Safety` section of this function's documentation, the caller of
522 // this function needs to guarantee that the passed-in lifetime is sufficiently long
523 // for the lifetime of the thread.
525 // Similarly, the `sys` implementation must guarantee that no references to the closure
526 // exist after the thread has terminated, which is signaled by `Thread::join`
531 mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(
542 ////////////////////////////////////////////////////////////////////////////////
544 ////////////////////////////////////////////////////////////////////////////////
546 /// Spawns a new thread, returning a [`JoinHandle`] for it.
548 /// The join handle provides a [`join`] method that can be used to join the spawned
549 /// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
550 /// the argument given to [`panic!`].
552 /// If the join handle is dropped, the spawned thread will implicitly be *detached*.
553 /// In this case, the spawned thread may no longer be joined.
554 /// (It is the responsibility of the program to either eventually join threads it
555 /// creates or detach them; otherwise, a resource leak will result.)
557 /// This call will create a thread using default parameters of [`Builder`], if you
558 /// want to specify the stack size or the name of the thread, use this API
561 /// As you can see in the signature of `spawn` there are two constraints on
562 /// both the closure given to `spawn` and its return value, let's explain them:
564 /// - The `'static` constraint means that the closure and its return value
565 /// must have a lifetime of the whole program execution. The reason for this
566 /// is that threads can outlive the lifetime they have been created in.
568 /// Indeed if the thread, and by extension its return value, can outlive their
569 /// caller, we need to make sure that they will be valid afterwards, and since
570 /// we *can't* know when it will return we need to have them valid as long as
571 /// possible, that is until the end of the program, hence the `'static`
573 /// - The [`Send`] constraint is because the closure will need to be passed
574 /// *by value* from the thread where it is spawned to the new thread. Its
575 /// return value will need to be passed from the new thread to the thread
576 /// where it is `join`ed.
577 /// As a reminder, the [`Send`] marker trait expresses that it is safe to be
578 /// passed from thread to thread. [`Sync`] expresses that it is safe to have a
579 /// reference be passed from thread to thread.
583 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
584 /// to recover from such errors.
588 /// Creating a thread.
593 /// let handler = thread::spawn(|| {
597 /// handler.join().unwrap();
600 /// As mentioned in the module documentation, threads are usually made to
601 /// communicate using [`channels`], here is how it usually looks.
603 /// This example also shows how to use `move`, in order to give ownership
604 /// of values to a thread.
608 /// use std::sync::mpsc::channel;
610 /// let (tx, rx) = channel();
612 /// let sender = thread::spawn(move || {
613 /// tx.send("Hello, thread".to_owned())
614 /// .expect("Unable to send on channel");
617 /// let receiver = thread::spawn(move || {
618 /// let value = rx.recv().expect("Unable to receive from channel");
619 /// println!("{value}");
622 /// sender.join().expect("The sender thread has panicked");
623 /// receiver.join().expect("The receiver thread has panicked");
626 /// A thread can also return a value through its [`JoinHandle`], you can use
627 /// this to make asynchronous computations (futures might be more appropriate
633 /// let computation = thread::spawn(|| {
634 /// // Some expensive computation.
638 /// let result = computation.join().unwrap();
639 /// println!("{result}");
642 /// [`channels`]: crate::sync::mpsc
643 /// [`join`]: JoinHandle::join
644 /// [`Err`]: crate::result::Result::Err
645 #[stable(feature = "rust1", since = "1.0.0")]
646 pub fn spawn<F, T>(f: F) -> JoinHandle<T>
652 Builder::new().spawn(f).expect("failed to spawn thread")
655 /// Gets a handle to the thread that invokes it.
659 /// Getting a handle to the current thread with `thread::current()`:
664 /// let handler = thread::Builder::new()
665 /// .name("named thread".into())
667 /// let handle = thread::current();
668 /// assert_eq!(handle.name(), Some("named thread"));
672 /// handler.join().unwrap();
675 #[stable(feature = "rust1", since = "1.0.0")]
676 pub fn current() -> Thread {
677 thread_info::current_thread().expect(
678 "use of std::thread::current() is not possible \
679 after the thread's local data has been destroyed",
683 /// Cooperatively gives up a timeslice to the OS scheduler.
685 /// This calls the underlying OS scheduler's yield primitive, signaling
686 /// that the calling thread is willing to give up its remaining timeslice
687 /// so that the OS may schedule other threads on the CPU.
689 /// A drawback of yielding in a loop is that if the OS does not have any
690 /// other ready threads to run on the current CPU, the thread will effectively
691 /// busy-wait, which wastes CPU time and energy.
693 /// Therefore, when waiting for events of interest, a programmer's first
694 /// choice should be to use synchronization devices such as [`channel`]s,
695 /// [`Condvar`]s, [`Mutex`]es or [`join`] since these primitives are
696 /// implemented in a blocking manner, giving up the CPU until the event
697 /// of interest has occurred which avoids repeated yielding.
699 /// `yield_now` should thus be used only rarely, mostly in situations where
700 /// repeated polling is required because there is no other suitable way to
701 /// learn when an event of interest has occurred.
708 /// thread::yield_now();
711 /// [`channel`]: crate::sync::mpsc
712 /// [`join`]: JoinHandle::join
713 /// [`Condvar`]: crate::sync::Condvar
714 /// [`Mutex`]: crate::sync::Mutex
715 #[stable(feature = "rust1", since = "1.0.0")]
717 imp::Thread::yield_now()
720 /// Determines whether the current thread is unwinding because of panic.
722 /// A common use of this feature is to poison shared resources when writing
723 /// unsafe code, by checking `panicking` when the `drop` is called.
725 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
726 /// already poison themselves when a thread panics while holding the lock.
728 /// This can also be used in multithreaded applications, in order to send a
729 /// message to other threads warning that a thread has panicked (e.g., for
730 /// monitoring purposes).
737 /// struct SomeStruct;
739 /// impl Drop for SomeStruct {
740 /// fn drop(&mut self) {
741 /// if thread::panicking() {
742 /// println!("dropped while unwinding");
744 /// println!("dropped while not unwinding");
751 /// let a = SomeStruct;
756 /// let b = SomeStruct;
761 /// [Mutex]: crate::sync::Mutex
764 #[stable(feature = "rust1", since = "1.0.0")]
765 pub fn panicking() -> bool {
766 panicking::panicking()
769 /// Puts the current thread to sleep for at least the specified amount of time.
771 /// The thread may sleep longer than the duration specified due to scheduling
772 /// specifics or platform-dependent functionality. It will never sleep less.
774 /// This function is blocking, and should not be used in `async` functions.
776 /// # Platform-specific behavior
778 /// On Unix platforms, the underlying syscall may be interrupted by a
779 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
780 /// the specified duration, this function may invoke that system call multiple
788 /// // Let's sleep for 2 seconds:
789 /// thread::sleep_ms(2000);
791 #[stable(feature = "rust1", since = "1.0.0")]
792 #[deprecated(since = "1.6.0", note = "replaced by `std::thread::sleep`")]
793 pub fn sleep_ms(ms: u32) {
794 sleep(Duration::from_millis(ms as u64))
797 /// Puts the current thread to sleep for at least the specified amount of time.
799 /// The thread may sleep longer than the duration specified due to scheduling
800 /// specifics or platform-dependent functionality. It will never sleep less.
802 /// This function is blocking, and should not be used in `async` functions.
804 /// # Platform-specific behavior
806 /// On Unix platforms, the underlying syscall may be interrupted by a
807 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
808 /// the specified duration, this function may invoke that system call multiple
810 /// Platforms which do not support nanosecond precision for sleeping will
811 /// have `dur` rounded up to the nearest granularity of time they can sleep for.
813 /// Currently, specifying a zero duration on Unix platforms returns immediately
814 /// without invoking the underlying [`nanosleep`] syscall, whereas on Windows
815 /// platforms the underlying [`Sleep`] syscall is always invoked.
816 /// If the intention is to yield the current time-slice you may want to use
817 /// [`yield_now`] instead.
819 /// [`nanosleep`]: https://linux.die.net/man/2/nanosleep
820 /// [`Sleep`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
825 /// use std::{thread, time};
827 /// let ten_millis = time::Duration::from_millis(10);
828 /// let now = time::Instant::now();
830 /// thread::sleep(ten_millis);
832 /// assert!(now.elapsed() >= ten_millis);
834 #[stable(feature = "thread_sleep", since = "1.4.0")]
835 pub fn sleep(dur: Duration) {
836 imp::Thread::sleep(dur)
839 /// Blocks unless or until the current thread's token is made available.
841 /// A call to `park` does not guarantee that the thread will remain parked
842 /// forever, and callers should be prepared for this possibility.
844 /// # park and unpark
846 /// Every thread is equipped with some basic low-level blocking support, via the
847 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
848 /// method. [`park`] blocks the current thread, which can then be resumed from
849 /// another thread by calling the [`unpark`] method on the blocked thread's
852 /// Conceptually, each [`Thread`] handle has an associated token, which is
853 /// initially not present:
855 /// * The [`thread::park`][`park`] function blocks the current thread unless or
856 /// until the token is available for its thread handle, at which point it
857 /// atomically consumes the token. It may also return *spuriously*, without
858 /// consuming the token. [`thread::park_timeout`] does the same, but allows
859 /// specifying a maximum time to block the thread for.
861 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
862 /// if it wasn't already. Because the token is initially absent, [`unpark`]
863 /// followed by [`park`] will result in the second call returning immediately.
865 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
866 /// locked and unlocked using `park` and `unpark`.
868 /// Notice that being unblocked does not imply any synchronization with someone
869 /// that unparked this thread, it could also be spurious.
870 /// For example, it would be a valid, but inefficient, implementation to make both [`park`] and
871 /// [`unpark`] return immediately without doing anything.
873 /// The API is typically used by acquiring a handle to the current thread,
874 /// placing that handle in a shared data structure so that other threads can
875 /// find it, and then `park`ing in a loop. When some desired condition is met, another
876 /// thread calls [`unpark`] on the handle.
878 /// The motivation for this design is twofold:
880 /// * It avoids the need to allocate mutexes and condvars when building new
881 /// synchronization primitives; the threads already provide basic
882 /// blocking/signaling.
884 /// * It can be implemented very efficiently on many platforms.
890 /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
891 /// use std::time::Duration;
893 /// let flag = Arc::new(AtomicBool::new(false));
894 /// let flag2 = Arc::clone(&flag);
896 /// let parked_thread = thread::spawn(move || {
897 /// // We want to wait until the flag is set. We *could* just spin, but using
898 /// // park/unpark is more efficient.
899 /// while !flag2.load(Ordering::Acquire) {
900 /// println!("Parking thread");
902 /// // We *could* get here spuriously, i.e., way before the 10ms below are over!
903 /// // But that is no problem, we are in a loop until the flag is set anyway.
904 /// println!("Thread unparked");
906 /// println!("Flag received");
909 /// // Let some time pass for the thread to be spawned.
910 /// thread::sleep(Duration::from_millis(10));
912 /// // Set the flag, and let the thread wake up.
913 /// // There is no race condition here, if `unpark`
914 /// // happens first, `park` will return immediately.
915 /// // Hence there is no risk of a deadlock.
916 /// flag.store(true, Ordering::Release);
917 /// println!("Unpark the thread");
918 /// parked_thread.thread().unpark();
920 /// parked_thread.join().unwrap();
923 /// [`unpark`]: Thread::unpark
924 /// [`thread::park_timeout`]: park_timeout
925 #[stable(feature = "rust1", since = "1.0.0")]
927 // SAFETY: park_timeout is called on the parker owned by this thread.
929 current().inner.as_ref().parker().park();
933 /// Use [`park_timeout`].
935 /// Blocks unless or until the current thread's token is made available or
936 /// the specified duration has been reached (may wake spuriously).
938 /// The semantics of this function are equivalent to [`park`] except
939 /// that the thread will be blocked for roughly no longer than `dur`. This
940 /// method should not be used for precise timing due to anomalies such as
941 /// preemption or platform differences that might not cause the maximum
942 /// amount of time waited to be precisely `ms` long.
944 /// See the [park documentation][`park`] for more detail.
945 #[stable(feature = "rust1", since = "1.0.0")]
946 #[deprecated(since = "1.6.0", note = "replaced by `std::thread::park_timeout`")]
947 pub fn park_timeout_ms(ms: u32) {
948 park_timeout(Duration::from_millis(ms as u64))
951 /// Blocks unless or until the current thread's token is made available or
952 /// the specified duration has been reached (may wake spuriously).
954 /// The semantics of this function are equivalent to [`park`][park] except
955 /// that the thread will be blocked for roughly no longer than `dur`. This
956 /// method should not be used for precise timing due to anomalies such as
957 /// preemption or platform differences that might not cause the maximum
958 /// amount of time waited to be precisely `dur` long.
960 /// See the [park documentation][park] for more details.
962 /// # Platform-specific behavior
964 /// Platforms which do not support nanosecond precision for sleeping will have
965 /// `dur` rounded up to the nearest granularity of time they can sleep for.
969 /// Waiting for the complete expiration of the timeout:
972 /// use std::thread::park_timeout;
973 /// use std::time::{Instant, Duration};
975 /// let timeout = Duration::from_secs(2);
976 /// let beginning_park = Instant::now();
978 /// let mut timeout_remaining = timeout;
980 /// park_timeout(timeout_remaining);
981 /// let elapsed = beginning_park.elapsed();
982 /// if elapsed >= timeout {
985 /// println!("restarting park_timeout after {elapsed:?}");
986 /// timeout_remaining = timeout - elapsed;
989 #[stable(feature = "park_timeout", since = "1.4.0")]
990 pub fn park_timeout(dur: Duration) {
991 // SAFETY: park_timeout is called on the parker owned by this thread.
993 current().inner.as_ref().parker().park_timeout(dur);
997 ////////////////////////////////////////////////////////////////////////////////
999 ////////////////////////////////////////////////////////////////////////////////
1001 /// A unique identifier for a running thread.
1003 /// A `ThreadId` is an opaque object that uniquely identifies each thread
1004 /// created during the lifetime of a process. `ThreadId`s are guaranteed not to
1005 /// be reused, even when a thread terminates. `ThreadId`s are under the control
1006 /// of Rust's standard library and there may not be any relationship between
1007 /// `ThreadId` and the underlying platform's notion of a thread identifier --
1008 /// the two concepts cannot, therefore, be used interchangeably. A `ThreadId`
1009 /// can be retrieved from the [`id`] method on a [`Thread`].
1014 /// use std::thread;
1016 /// let other_thread = thread::spawn(|| {
1017 /// thread::current().id()
1020 /// let other_thread_id = other_thread.join().unwrap();
1021 /// assert!(thread::current().id() != other_thread_id);
1024 /// [`id`]: Thread::id
1025 #[stable(feature = "thread_id", since = "1.19.0")]
1026 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1027 pub struct ThreadId(NonZeroU64);
1030 // Generate a new unique thread ID.
1031 fn new() -> ThreadId {
1032 // It is UB to attempt to acquire this mutex reentrantly!
1033 static GUARD: mutex::StaticMutex = mutex::StaticMutex::new();
1034 static mut COUNTER: u64 = 1;
1037 let guard = GUARD.lock();
1039 // If we somehow use up all our bits, panic so that we're not
1040 // covering up subtle bugs of IDs being reused.
1041 if COUNTER == u64::MAX {
1042 drop(guard); // in case the panic handler ends up calling `ThreadId::new()`, avoid reentrant lock acquire.
1043 panic!("failed to generate unique thread ID: bitspace exhausted");
1049 ThreadId(NonZeroU64::new(id).unwrap())
1053 /// This returns a numeric identifier for the thread identified by this
1056 /// As noted in the documentation for the type itself, it is essentially an
1057 /// opaque ID, but is guaranteed to be unique for each thread. The returned
1058 /// value is entirely opaque -- only equality testing is stable. Note that
1059 /// it is not guaranteed which values new threads will return, and this may
1060 /// change across Rust versions.
1062 #[unstable(feature = "thread_id_value", issue = "67939")]
1063 pub fn as_u64(&self) -> NonZeroU64 {
1068 ////////////////////////////////////////////////////////////////////////////////
1070 ////////////////////////////////////////////////////////////////////////////////
1072 /// The internal representation of a `Thread` handle
1074 name: Option<CString>, // Guaranteed to be UTF-8
1080 fn parker(self: Pin<&Self>) -> Pin<&Parker> {
1081 unsafe { Pin::map_unchecked(self, |inner| &inner.parker) }
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 /// A handle to a thread.
1089 /// Threads are represented via the `Thread` type, which you can get in one of
1092 /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1093 /// function, and calling [`thread`][`JoinHandle::thread`] on the
1095 /// * By requesting the current thread, using the [`thread::current`] function.
1097 /// The [`thread::current`] function is available even for threads not spawned
1098 /// by the APIs of this module.
1100 /// There is usually no need to create a `Thread` struct yourself, one
1101 /// should instead use a function like `spawn` to create new threads, see the
1102 /// docs of [`Builder`] and [`spawn`] for more details.
1104 /// [`thread::current`]: current
1106 inner: Pin<Arc<Inner>>,
1110 // Used only internally to construct a thread object without spawning
1111 // Panics if the name contains nuls.
1112 pub(crate) fn new(name: Option<CString>) -> Thread {
1113 // We have to use `unsafe` here to constuct the `Parker` in-place,
1114 // which is required for the UNIX implementation.
1116 // SAFETY: We pin the Arc immediately after creation, so its address never
1118 let inner = unsafe {
1119 let mut arc = Arc::<Inner>::new_uninit();
1120 let ptr = Arc::get_mut_unchecked(&mut arc).as_mut_ptr();
1121 addr_of_mut!((*ptr).name).write(name);
1122 addr_of_mut!((*ptr).id).write(ThreadId::new());
1123 Parker::new(addr_of_mut!((*ptr).parker));
1124 Pin::new_unchecked(arc.assume_init())
1130 /// Atomically makes the handle's token available if it is not already.
1132 /// Every thread is equipped with some basic low-level blocking support, via
1133 /// the [`park`][park] function and the `unpark()` method. These can be
1134 /// used as a more CPU-efficient implementation of a spinlock.
1136 /// See the [park documentation][park] for more details.
1141 /// use std::thread;
1142 /// use std::time::Duration;
1144 /// let parked_thread = thread::Builder::new()
1146 /// println!("Parking thread");
1148 /// println!("Thread unparked");
1152 /// // Let some time pass for the thread to be spawned.
1153 /// thread::sleep(Duration::from_millis(10));
1155 /// println!("Unpark the thread");
1156 /// parked_thread.thread().unpark();
1158 /// parked_thread.join().unwrap();
1160 #[stable(feature = "rust1", since = "1.0.0")]
1162 pub fn unpark(&self) {
1163 self.inner.as_ref().parker().unpark();
1166 /// Gets the thread's unique identifier.
1171 /// use std::thread;
1173 /// let other_thread = thread::spawn(|| {
1174 /// thread::current().id()
1177 /// let other_thread_id = other_thread.join().unwrap();
1178 /// assert!(thread::current().id() != other_thread_id);
1180 #[stable(feature = "thread_id", since = "1.19.0")]
1182 pub fn id(&self) -> ThreadId {
1186 /// Gets the thread's name.
1188 /// For more information about named threads, see
1189 /// [this module-level documentation][naming-threads].
1193 /// Threads by default have no name specified:
1196 /// use std::thread;
1198 /// let builder = thread::Builder::new();
1200 /// let handler = builder.spawn(|| {
1201 /// assert!(thread::current().name().is_none());
1204 /// handler.join().unwrap();
1207 /// Thread with a specified name:
1210 /// use std::thread;
1212 /// let builder = thread::Builder::new()
1213 /// .name("foo".into());
1215 /// let handler = builder.spawn(|| {
1216 /// assert_eq!(thread::current().name(), Some("foo"))
1219 /// handler.join().unwrap();
1222 /// [naming-threads]: ./index.html#naming-threads
1223 #[stable(feature = "rust1", since = "1.0.0")]
1225 pub fn name(&self) -> Option<&str> {
1226 self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
1229 fn cname(&self) -> Option<&CStr> {
1230 self.inner.name.as_deref()
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 impl fmt::Debug for Thread {
1236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237 f.debug_struct("Thread")
1238 .field("id", &self.id())
1239 .field("name", &self.name())
1240 .finish_non_exhaustive()
1244 ////////////////////////////////////////////////////////////////////////////////
1246 ////////////////////////////////////////////////////////////////////////////////
1248 /// A specialized [`Result`] type for threads.
1250 /// Indicates the manner in which a thread exited.
1252 /// The value contained in the `Result::Err` variant
1253 /// is the value the thread panicked with;
1254 /// that is, the argument the `panic!` macro was called with.
1255 /// Unlike with normal errors, this value doesn't implement
1256 /// the [`Error`](crate::error::Error) trait.
1258 /// Thus, a sensible way to handle a thread panic is to either:
1260 /// 1. propagate the panic with [`std::panic::resume_unwind`]
1261 /// 2. or in case the thread is intended to be a subsystem boundary
1262 /// that is supposed to isolate system-level failures,
1263 /// match on the `Err` variant and handle the panic in an appropriate way
1265 /// A thread that completes without panicking is considered to exit successfully.
1269 /// Matching on the result of a joined thread:
1272 /// use std::{fs, thread, panic};
1274 /// fn copy_in_thread() -> thread::Result<()> {
1275 /// thread::spawn(|| {
1276 /// fs::copy("foo.txt", "bar.txt").unwrap();
1281 /// match copy_in_thread() {
1282 /// Ok(_) => println!("copy succeeded"),
1283 /// Err(e) => panic::resume_unwind(e),
1288 /// [`Result`]: crate::result::Result
1289 /// [`std::panic::resume_unwind`]: crate::panic::resume_unwind
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
1293 // This packet is used to communicate the return value between the spawned
1294 // thread and the rest of the program. It is shared through an `Arc` and
1295 // there's no need for a mutex here because synchronization happens with `join()`
1296 // (the caller will never read this packet until the thread has exited).
1298 // An Arc to the packet is stored into a `JoinInner` which in turns is placed
1300 struct Packet<'scope, T> {
1301 scope: Option<&'scope scoped::ScopeData>,
1302 result: UnsafeCell<Option<Result<T>>>,
1305 // Due to the usage of `UnsafeCell` we need to manually implement Sync.
1306 // The type `T` should already always be Send (otherwise the thread could not
1307 // have been created) and the Packet is Sync because all access to the
1308 // `UnsafeCell` synchronized (by the `join()` boundary), and `ScopeData` is Sync.
1309 unsafe impl<'scope, T: Sync> Sync for Packet<'scope, T> {}
1311 impl<'scope, T> Drop for Packet<'scope, T> {
1312 fn drop(&mut self) {
1313 // If this packet was for a thread that ran in a scope, the thread
1314 // panicked, and nobody consumed the panic payload, we make sure
1315 // the scope function will panic.
1316 let unhandled_panic = matches!(self.result.get_mut(), Some(Err(_)));
1317 // Drop the result without causing unwinding.
1318 // This is only relevant for threads that aren't join()ed, as
1319 // join() will take the `result` and set it to None, such that
1320 // there is nothing left to drop here.
1321 // If this panics, we should handle that, because we're outside the
1322 // outermost `catch_unwind` of our thread.
1323 // We just abort in that case, since there's nothing else we can do.
1324 // (And even if we tried to handle it somehow, we'd also need to handle
1325 // the case where the panic payload we get out of it also panics on
1326 // drop, and so on. See issue #86027.)
1327 if let Err(_) = panic::catch_unwind(panic::AssertUnwindSafe(|| {
1328 *self.result.get_mut() = None;
1330 rtabort!("thread result panicked on drop");
1332 // Book-keeping so the scope knows when it's done.
1333 if let Some(scope) = self.scope {
1334 // Now that there will be no more user code running on this thread
1335 // that can use 'scope, mark the thread as 'finished'.
1336 // It's important we only do this after the `result` has been dropped,
1337 // since dropping it might still use things it borrowed from 'scope.
1338 scope.decrement_num_running_threads(unhandled_panic);
1343 /// Inner representation for JoinHandle
1344 struct JoinInner<'scope, T> {
1345 native: imp::Thread,
1347 packet: Arc<Packet<'scope, T>>,
1350 impl<'scope, T> JoinInner<'scope, T> {
1351 fn join(mut self) -> Result<T> {
1353 Arc::get_mut(&mut self.packet).unwrap().result.get_mut().take().unwrap()
1357 /// An owned permission to join on a thread (block on its termination).
1359 /// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1360 /// means that there is no longer any handle to the thread and no way to `join`
1363 /// Due to platform restrictions, it is not possible to [`Clone`] this
1364 /// handle: the ability to join a thread is a uniquely-owned permission.
1366 /// This `struct` is created by the [`thread::spawn`] function and the
1367 /// [`thread::Builder::spawn`] method.
1371 /// Creation from [`thread::spawn`]:
1374 /// use std::thread;
1376 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1377 /// // some work here
1381 /// Creation from [`thread::Builder::spawn`]:
1384 /// use std::thread;
1386 /// let builder = thread::Builder::new();
1388 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1389 /// // some work here
1393 /// A thread being detached and outliving the thread that spawned it:
1396 /// use std::thread;
1397 /// use std::time::Duration;
1399 /// let original_thread = thread::spawn(|| {
1400 /// let _detached_thread = thread::spawn(|| {
1401 /// // Here we sleep to make sure that the first thread returns before.
1402 /// thread::sleep(Duration::from_millis(10));
1403 /// // This will be called, even though the JoinHandle is dropped.
1404 /// println!("♫ Still alive ♫");
1408 /// original_thread.join().expect("The thread being joined has panicked");
1409 /// println!("Original thread is joined.");
1411 /// // We make sure that the new thread has time to run, before the main
1412 /// // thread returns.
1414 /// thread::sleep(Duration::from_millis(1000));
1417 /// [`thread::Builder::spawn`]: Builder::spawn
1418 /// [`thread::spawn`]: spawn
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 pub struct JoinHandle<T>(JoinInner<'static, T>);
1422 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1423 unsafe impl<T> Send for JoinHandle<T> {}
1424 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1425 unsafe impl<T> Sync for JoinHandle<T> {}
1427 impl<T> JoinHandle<T> {
1428 /// Extracts a handle to the underlying thread.
1433 /// use std::thread;
1435 /// let builder = thread::Builder::new();
1437 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1438 /// // some work here
1441 /// let thread = join_handle.thread();
1442 /// println!("thread id: {:?}", thread.id());
1444 #[stable(feature = "rust1", since = "1.0.0")]
1446 pub fn thread(&self) -> &Thread {
1450 /// Waits for the associated thread to finish.
1452 /// This function will return immediately if the associated thread has already finished.
1454 /// In terms of [atomic memory orderings], the completion of the associated
1455 /// thread synchronizes with this function returning. In other words, all
1456 /// operations performed by that thread [happen
1457 /// before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) all
1458 /// operations that happen after `join` returns.
1460 /// If the associated thread panics, [`Err`] is returned with the parameter given
1463 /// [`Err`]: crate::result::Result::Err
1464 /// [atomic memory orderings]: crate::sync::atomic
1468 /// This function may panic on some platforms if a thread attempts to join
1469 /// itself or otherwise may create a deadlock with joining threads.
1474 /// use std::thread;
1476 /// let builder = thread::Builder::new();
1478 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1479 /// // some work here
1481 /// join_handle.join().expect("Couldn't join on the associated thread");
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 pub fn join(self) -> Result<T> {
1488 /// Checks if the associated thread has finished running its main function.
1490 /// This might return `true` for a brief moment after the thread's main
1491 /// function has returned, but before the thread itself has stopped running.
1492 /// However, once this returns `true`, [`join`][Self::join] can be expected
1493 /// to return quickly, without blocking for any significant amount of time.
1495 /// This function does not block. To block while waiting on the thread to finish,
1496 /// use [`join`][Self::join].
1497 #[stable(feature = "thread_is_running", since = "1.61.0")]
1498 pub fn is_finished(&self) -> bool {
1499 Arc::strong_count(&self.0.packet) == 1
1503 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1504 fn as_inner(&self) -> &imp::Thread {
1509 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1510 fn into_inner(self) -> imp::Thread {
1515 #[stable(feature = "std_debug", since = "1.16.0")]
1516 impl<T> fmt::Debug for JoinHandle<T> {
1517 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1518 f.debug_struct("JoinHandle").finish_non_exhaustive()
1522 fn _assert_sync_and_send() {
1523 fn _assert_both<T: Send + Sync>() {}
1524 _assert_both::<JoinHandle<()>>();
1525 _assert_both::<Thread>();
1528 /// Returns an estimate of the default amount of parallelism a program should use.
1530 /// Parallelism is a resource. A given machine provides a certain capacity for
1531 /// parallelism, i.e., a bound on the number of computations it can perform
1532 /// simultaneously. This number often corresponds to the amount of CPUs a
1533 /// computer has, but it may diverge in various cases.
1535 /// Host environments such as VMs or container orchestrators may want to
1536 /// restrict the amount of parallelism made available to programs in them. This
1537 /// is often done to limit the potential impact of (unintentionally)
1538 /// resource-intensive programs on other programs running on the same machine.
1542 /// The purpose of this API is to provide an easy and portable way to query
1543 /// the default amount of parallelism the program should use. Among other things it
1544 /// does not expose information on NUMA regions, does not account for
1545 /// differences in (co)processor capabilities or current system load,
1546 /// and will not modify the program's global state in order to more accurately
1547 /// query the amount of available parallelism.
1549 /// Where both fixed steady-state and burst limits are available the steady-state
1550 /// capacity will be used to ensure more predictable latencies.
1552 /// Resource limits can be changed during the runtime of a program, therefore the value is
1553 /// not cached and instead recomputed every time this function is called. It should not be
1554 /// called from hot code.
1556 /// The value returned by this function should be considered a simplified
1557 /// approximation of the actual amount of parallelism available at any given
1558 /// time. To get a more detailed or precise overview of the amount of
1559 /// parallelism available to the program, you may wish to use
1560 /// platform-specific APIs as well. The following platform limitations currently
1561 /// apply to `available_parallelism`:
1564 /// - It may undercount the amount of parallelism available on systems with more
1565 /// than 64 logical CPUs. However, programs typically need specific support to
1566 /// take advantage of more than 64 logical CPUs, and in the absence of such
1567 /// support, the number returned by this function accurately reflects the
1568 /// number of logical CPUs the program can use by default.
1569 /// - It may overcount the amount of parallelism available on systems limited by
1570 /// process-wide affinity masks, or job object limitations.
1573 /// - It may overcount the amount of parallelism available when limited by a
1574 /// process-wide affinity mask or cgroup quotas and cgroup2 fs or `sched_getaffinity()` can't be
1575 /// queried, e.g. due to sandboxing.
1576 /// - It may undercount the amount of parallelism if the current thread's affinity mask
1577 /// does not reflect the process' cpuset, e.g. due to pinned threads.
1580 /// - It may overcount the amount of parallelism available when running in a VM
1581 /// with CPU usage limits (e.g. an overcommitted host).
1585 /// This function will, but is not limited to, return errors in the following
1588 /// - If the amount of parallelism is not known for the target platform.
1589 /// - If the program lacks permission to query the amount of parallelism made
1590 /// available to it.
1595 /// # #![allow(dead_code)]
1596 /// use std::{io, thread};
1598 /// fn main() -> io::Result<()> {
1599 /// let count = thread::available_parallelism()?.get();
1600 /// assert!(count >= 1_usize);
1604 #[doc(alias = "available_concurrency")] // Alias for a previous name we gave this API on unstable.
1605 #[doc(alias = "hardware_concurrency")] // Alias for C++ `std::thread::hardware_concurrency`.
1606 #[doc(alias = "num_cpus")] // Alias for a popular ecosystem crate which provides similar functionality.
1607 #[stable(feature = "available_parallelism", since = "1.59.0")]
1608 pub fn available_parallelism() -> io::Result<NonZeroUsize> {
1609 imp::available_parallelism()