Skip to main content

std/thread/
functions.rs

1//! Free functions.
2
3use super::builder::Builder;
4use super::current::current;
5use super::join_handle::JoinHandle;
6use crate::mem::forget;
7use crate::num::NonZero;
8use crate::sys::thread as imp;
9use crate::time::{Duration, Instant};
10use crate::{io, panicking};
11
12/// Spawns a new thread, returning a [`JoinHandle`] for it.
13///
14/// The join handle provides a [`join`] method that can be used to join the spawned
15/// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
16/// the argument given to [`panic!`].
17///
18/// If the join handle is dropped, the spawned thread will implicitly be *detached*.
19/// In this case, the spawned thread may no longer be joined.
20/// (It is the responsibility of the program to either eventually join threads it
21/// creates or detach them; otherwise, a resource leak will result.)
22///
23/// This function creates a thread with the default parameters of [`Builder`].
24/// To specify the new thread's stack size or the name, use [`Builder::spawn`].
25///
26/// As you can see in the signature of `spawn` there are two constraints on
27/// both the closure given to `spawn` and its return value, let's explain them:
28///
29/// - The `'static` constraint means that the closure and its return value
30///   must have a lifetime of the whole program execution. The reason for this
31///   is that threads can outlive the lifetime they have been created in.
32///
33///   Indeed if the thread, and by extension its return value, can outlive their
34///   caller, we need to make sure that they will be valid afterwards, and since
35///   we *can't* know when it will return we need to have them valid as long as
36///   possible, that is until the end of the program, hence the `'static`
37///   lifetime.
38/// - The [`Send`] constraint is because the closure will need to be passed
39///   *by value* from the thread where it is spawned to the new thread. Its
40///   return value will need to be passed from the new thread to the thread
41///   where it is `join`ed.
42///   As a reminder, the [`Send`] marker trait expresses that it is safe to be
43///   passed from thread to thread. [`Sync`] expresses that it is safe to have a
44///   reference be passed from thread to thread.
45///
46/// # Panics
47///
48/// Panics if the OS fails to create a thread; use [`Builder::spawn`]
49/// to recover from such errors.
50///
51/// # Examples
52///
53/// Creating a thread.
54///
55/// ```
56/// use std::thread;
57///
58/// let handler = thread::spawn(|| {
59///     // thread code
60/// });
61///
62/// handler.join().unwrap();
63/// ```
64///
65/// As mentioned in the module documentation, threads are usually made to
66/// communicate using [`channels`], here is how it usually looks.
67///
68/// This example also shows how to use `move`, in order to give ownership
69/// of values to a thread.
70///
71/// ```
72/// use std::thread;
73/// use std::sync::mpsc::channel;
74///
75/// let (tx, rx) = channel();
76///
77/// let sender = thread::spawn(move || {
78///     tx.send("Hello, thread".to_owned())
79///         .expect("Unable to send on channel");
80/// });
81///
82/// let receiver = thread::spawn(move || {
83///     let value = rx.recv().expect("Unable to receive from channel");
84///     println!("{value}");
85/// });
86///
87/// sender.join().expect("The sender thread has panicked");
88/// receiver.join().expect("The receiver thread has panicked");
89/// ```
90///
91/// A thread can also return a value through its [`JoinHandle`], you can use
92/// this to make asynchronous computations (futures might be more appropriate
93/// though).
94///
95/// ```
96/// use std::thread;
97///
98/// let computation = thread::spawn(|| {
99///     // Some expensive computation.
100///     42
101/// });
102///
103/// let result = computation.join().unwrap();
104/// println!("{result}");
105/// ```
106///
107/// # Notes
108///
109/// This function has the same minimal guarantee regarding "foreign" unwinding operations (e.g.
110/// an exception thrown from C++ code, or a `panic!` in Rust code compiled or linked with a
111/// different runtime) as [`catch_unwind`]; namely, if the thread created with `thread::spawn`
112/// unwinds all the way to the root with such an exception, one of two behaviors are possible,
113/// and it is unspecified which will occur:
114///
115/// * The process aborts.
116/// * The process does not abort, and [`join`] will return a `Result::Err`
117///   containing an opaque type.
118///
119/// [`catch_unwind`]: ../../std/panic/fn.catch_unwind.html
120/// [`channels`]: crate::sync::mpsc
121/// [`join`]: JoinHandle::join
122/// [`Err`]: crate::result::Result::Err
123#[ferrocene::prevalidated]
124#[stable(feature = "rust1", since = "1.0.0")]
125#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
126pub fn spawn<F, T>(f: F) -> JoinHandle<T>
127where
128    F: FnOnce() -> T,
129    F: Send + 'static,
130    T: Send + 'static,
131{
132    Builder::new().spawn(f).expect("failed to spawn thread")
133}
134
135/// Cooperatively gives up a timeslice to the OS scheduler.
136///
137/// This calls the underlying OS scheduler's yield primitive, signaling
138/// that the calling thread is willing to give up its remaining timeslice
139/// so that the OS may schedule other threads on the CPU.
140///
141/// A drawback of yielding in a loop is that if the OS does not have any
142/// other ready threads to run on the current CPU, the thread will effectively
143/// busy-wait, which wastes CPU time and energy.
144///
145/// Therefore, when waiting for events of interest, a programmer's first
146/// choice should be to use synchronization devices such as [`channel`]s,
147/// [`Condvar`]s, [`Mutex`]es or [`join`] since these primitives are
148/// implemented in a blocking manner, giving up the CPU until the event
149/// of interest has occurred which avoids repeated yielding.
150///
151/// `yield_now` should thus be used only rarely, mostly in situations where
152/// repeated polling is required because there is no other suitable way to
153/// learn when an event of interest has occurred.
154///
155/// # Examples
156///
157/// ```
158/// use std::thread;
159///
160/// thread::yield_now();
161/// ```
162///
163/// [`channel`]: crate::sync::mpsc
164/// [`join`]: JoinHandle::join
165/// [`Condvar`]: crate::sync::Condvar
166/// [`Mutex`]: crate::sync::Mutex
167#[stable(feature = "rust1", since = "1.0.0")]
168pub fn yield_now() {
169    #[allow(ferrocene::unvalidated, reason = "defer validating platform-specifics")]
170    imp::yield_now()
171}
172
173/// Determines whether the current thread is panicking.
174///
175/// This returns `true` both when the thread is unwinding due to a panic,
176/// or executing a panic hook. Note that the latter case will still happen
177/// when `panic=abort` is set.
178///
179/// A common use of this feature is to poison shared resources when writing
180/// unsafe code, by checking `panicking` when the `drop` is called.
181///
182/// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
183/// already poison themselves when a thread panics while holding the lock.
184///
185/// This can also be used in multithreaded applications, in order to send a
186/// message to other threads warning that a thread has panicked (e.g., for
187/// monitoring purposes).
188///
189/// # Examples
190///
191/// ```should_panic
192/// use std::thread;
193///
194/// struct SomeStruct;
195///
196/// impl Drop for SomeStruct {
197///     fn drop(&mut self) {
198///         if thread::panicking() {
199///             println!("dropped while unwinding");
200///         } else {
201///             println!("dropped while not unwinding");
202///         }
203///     }
204/// }
205///
206/// {
207///     print!("a: ");
208///     let a = SomeStruct;
209/// }
210///
211/// {
212///     print!("b: ");
213///     let b = SomeStruct;
214///     panic!()
215/// }
216/// ```
217///
218/// [Mutex]: crate::sync::Mutex
219#[inline]
220#[must_use]
221#[stable(feature = "rust1", since = "1.0.0")]
222pub fn panicking() -> bool {
223    panicking::panicking()
224}
225
226/// Uses [`sleep`].
227///
228/// Puts the current thread to sleep for at least the specified amount of time.
229///
230/// The thread may sleep longer than the duration specified due to scheduling
231/// specifics or platform-dependent functionality. It will never sleep less.
232///
233/// This function is blocking, and should not be used in `async` functions.
234///
235/// # Platform-specific behavior
236///
237/// On Unix platforms, the underlying syscall may be interrupted by a
238/// spurious wakeup or signal handler. To ensure the sleep occurs for at least
239/// the specified duration, this function may invoke that system call multiple
240/// times.
241///
242/// # Examples
243///
244/// ```no_run
245/// use std::thread;
246///
247/// // Let's sleep for 2 seconds:
248/// thread::sleep_ms(2000);
249/// ```
250#[stable(feature = "rust1", since = "1.0.0")]
251#[deprecated(since = "1.6.0", note = "replaced by `std::thread::sleep`")]
252pub fn sleep_ms(ms: u32) {
253    sleep(Duration::from_millis(ms as u64))
254}
255
256/// Puts the current thread to sleep for at least the specified amount of time.
257///
258/// The thread may sleep longer than the duration specified due to scheduling
259/// specifics or platform-dependent functionality. It will never sleep less.
260///
261/// This function is blocking, and should not be used in `async` functions.
262///
263/// # Platform-specific behavior
264///
265/// On Unix platforms, the underlying syscall may be interrupted by a
266/// spurious wakeup or signal handler. To ensure the sleep occurs for at least
267/// the specified duration, this function may invoke that system call multiple
268/// times.
269/// Platforms which do not support nanosecond precision for sleeping will
270/// have `dur` rounded up to the nearest granularity of time they can sleep for.
271///
272/// Currently, specifying a zero duration on Unix platforms returns immediately
273/// without invoking the underlying [`nanosleep`] syscall, whereas on Windows
274/// platforms the underlying [`Sleep`] syscall is always invoked.
275/// If the intention is to yield the current time-slice you may want to use
276/// [`yield_now`] instead.
277///
278/// [`nanosleep`]: https://linux.die.net/man/2/nanosleep
279/// [`Sleep`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
280///
281/// # Examples
282///
283/// ```no_run
284/// use std::{thread, time};
285///
286/// let ten_millis = time::Duration::from_millis(10);
287/// let now = time::Instant::now();
288///
289/// thread::sleep(ten_millis);
290///
291/// assert!(now.elapsed() >= ten_millis);
292/// ```
293#[stable(feature = "thread_sleep", since = "1.4.0")]
294pub fn sleep(dur: Duration) {
295    imp::sleep(dur)
296}
297
298/// Puts the current thread to sleep until the specified deadline has passed.
299///
300/// If the deadline has already passed at the time this function is called, it
301/// will return immediately. Note that the thread may still be asleep after the
302/// deadline specified due to scheduling specifics or platform-dependent
303/// functionality. It will never wake before.
304///
305/// This function is blocking, and should not be used in `async` functions.
306///
307/// # Platform-specific behavior
308///
309/// In most cases this function will call an OS specific function. Where that
310/// is not supported [`sleep`] is used. Those platforms are referred to as other
311/// in the table below.
312///
313/// # Underlying System calls
314///
315/// The following system calls are [currently] being used:
316///
317/// |  Platform |               System call                                            |
318/// |-----------|----------------------------------------------------------------------|
319/// | Linux     | [`clock_nanosleep`] (Monotonic Clock)                                |
320/// | BSD except OpenBSD | [`clock_nanosleep`] (Monotonic Clock)                       |
321/// | Android   | [`clock_nanosleep`] (Monotonic Clock)                                |
322/// | Solaris   | [`clock_nanosleep`] (Monotonic Clock)                                |
323/// | Illumos   | [`clock_nanosleep`] (Monotonic Clock)                                |
324/// | Dragonfly | [`clock_nanosleep`] (Monotonic Clock)                                |
325/// | Hurd      | [`clock_nanosleep`] (Monotonic Clock)                                |
326/// | Vxworks   | [`clock_nanosleep`] (Monotonic Clock)                                |
327/// | Apple     | `mach_wait_until`                                                    |
328/// | Fuchsia   | [`zx_nanosleep`]                                                     |
329/// | Other     | `sleep_until` uses [`sleep`] and does not issue a syscall itself     |
330///
331/// [currently]: crate::io#platform-specific-behavior
332/// [`clock_nanosleep`]: https://linux.die.net/man/3/clock_nanosleep
333/// [`zx_nanosleep`]: https://fuchsia.dev/reference/syscalls/nanosleep
334///
335/// **Disclaimer:** These system calls might change over time.
336///
337/// # Examples
338///
339/// A simple game loop that limits the game to 60 frames per second.
340///
341/// ```no_run
342/// #![feature(thread_sleep_until)]
343/// # use std::time::{Duration, Instant};
344/// # use std::thread;
345/// #
346/// # fn update() {}
347/// # fn render() {}
348/// #
349/// let max_fps = 60.0;
350/// let frame_time = Duration::from_secs_f32(1.0/max_fps);
351/// let mut next_frame = Instant::now();
352/// loop {
353///     thread::sleep_until(next_frame);
354///     next_frame += frame_time;
355///     update();
356///     render();
357/// }
358/// ```
359///
360/// A slow API we must not call too fast and which takes a few
361/// tries before succeeding. By using `sleep_until` the time the
362/// API call takes does not influence when we retry or when we give up
363///
364/// ```no_run
365/// #![feature(thread_sleep_until)]
366/// # use std::time::{Duration, Instant};
367/// # use std::thread;
368/// #
369/// # enum Status {
370/// #     Ready(usize),
371/// #     Waiting,
372/// # }
373/// # fn slow_web_api_call() -> Status { Status::Ready(42) }
374/// #
375/// # const MAX_DURATION: Duration = Duration::from_secs(10);
376/// #
377/// # fn try_api_call() -> Result<usize, ()> {
378/// let deadline = Instant::now() + MAX_DURATION;
379/// let delay = Duration::from_millis(250);
380/// let mut next_attempt = Instant::now();
381/// loop {
382///     if Instant::now() > deadline {
383///         break Err(());
384///     }
385///     if let Status::Ready(data) = slow_web_api_call() {
386///         break Ok(data);
387///     }
388///
389///     next_attempt = deadline.min(next_attempt + delay);
390///     thread::sleep_until(next_attempt);
391/// }
392/// # }
393/// # let _data = try_api_call();
394/// ```
395#[unstable(feature = "thread_sleep_until", issue = "113752")]
396pub fn sleep_until(deadline: Instant) {
397    imp::sleep_until(deadline)
398}
399
400/// Used to ensure that `park` and `park_timeout` do not unwind, as that can
401/// cause undefined behavior if not handled correctly (see #102398 for context).
402struct PanicGuard;
403
404impl Drop for PanicGuard {
405    fn drop(&mut self) {
406        rtabort!("an irrecoverable error occurred while synchronizing threads")
407    }
408}
409
410/// Blocks unless or until the current thread's token is made available.
411///
412/// A call to `park` does not guarantee that the thread will remain parked
413/// forever, and callers should be prepared for this possibility. However,
414/// it is guaranteed that this function will not panic (it may abort the
415/// process if the implementation encounters some rare errors).
416///
417/// # `park` and `unpark`
418///
419/// Every thread is equipped with some basic low-level blocking support, via the
420/// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
421/// method. [`park`] blocks the current thread, which can then be resumed from
422/// another thread by calling the [`unpark`] method on the blocked thread's
423/// handle.
424///
425/// Conceptually, each [`Thread`] handle has an associated token, which is
426/// initially not present:
427///
428/// * The [`thread::park`][`park`] function blocks the current thread unless or
429///   until the token is available for its thread handle, at which point it
430///   atomically consumes the token. It may also return *spuriously*, without
431///   consuming the token. [`thread::park_timeout`] does the same, but allows
432///   specifying a maximum time to block the thread for.
433///
434/// * The [`unpark`] method on a [`Thread`] atomically makes the token available
435///   if it wasn't already. Because the token can be held by a thread even if it is currently not
436///   parked, [`unpark`] followed by [`park`] will result in the second call returning immediately.
437///   However, note that to rely on this guarantee, you need to make sure that your `unpark` happens
438///   after all `park` that may be done by other data structures!
439///
440/// The API is typically used by acquiring a handle to the current thread, placing that handle in a
441/// shared data structure so that other threads can find it, and then `park`ing in a loop. When some
442/// desired condition is met, another thread calls [`unpark`] on the handle. The last bullet point
443/// above guarantees that even if the `unpark` occurs before the thread is finished `park`ing, it
444/// will be woken up properly.
445///
446/// Note that the coordination via the shared data structure is crucial: If you `unpark` a thread
447/// without first establishing that it is about to be `park`ing within your code, that `unpark` may
448/// get consumed by a *different* `park` in the same thread, leading to a deadlock. This also means
449/// you must not call unknown code between setting up for parking and calling `park`; for instance,
450/// if you invoke `println!`, that may itself call `park` and thus consume your `unpark` and cause a
451/// deadlock.
452///
453/// The motivation for this design is twofold:
454///
455/// * It avoids the need to allocate mutexes and condvars when building new
456///   synchronization primitives; the threads already provide basic
457///   blocking/signaling.
458///
459/// * It can be implemented very efficiently on many platforms.
460///
461/// # Memory Ordering
462///
463/// Calls to `unpark` _synchronize-with_ calls to `park`, meaning that memory
464/// operations performed before a call to `unpark` are made visible to the thread that
465/// consumes the token and returns from `park`. Note that all `park` and `unpark`
466/// operations for a given thread form a total order and _all_ prior `unpark` operations
467/// synchronize-with `park`.
468///
469/// In atomic ordering terms, `unpark` performs a `Release` operation and `park`
470/// performs the corresponding `Acquire` operation. Calls to `unpark` for the same
471/// thread form a [release sequence].
472///
473/// Note that being unblocked does not imply a call was made to `unpark`, because
474/// wakeups can also be spurious. For example, a valid, but inefficient,
475/// implementation could have `park` and `unpark` return immediately without doing anything,
476/// making *all* wakeups spurious.
477///
478/// # Examples
479///
480/// ```
481/// use std::thread;
482/// use std::sync::atomic::{Ordering, AtomicBool};
483/// use std::time::Duration;
484///
485/// static QUEUED: AtomicBool = AtomicBool::new(false);
486/// static FLAG: AtomicBool = AtomicBool::new(false);
487///
488/// let parked_thread = thread::spawn(move || {
489///     println!("Thread spawned");
490///     // Signal that we are going to `park`. Between this store and our `park`, there may
491///     // be no other `park`, or else that `park` could consume our `unpark` token!
492///     QUEUED.store(true, Ordering::Release);
493///     // We want to wait until the flag is set. We *could* just spin, but using
494///     // park/unpark is more efficient.
495///     while !FLAG.load(Ordering::Acquire) {
496///         // We can *not* use `println!` here since that could use thread parking internally.
497///         thread::park();
498///         // We *could* get here spuriously, i.e., way before the 10ms below are over!
499///         // But that is no problem, we are in a loop until the flag is set anyway.
500///     }
501///     println!("Flag received");
502/// });
503///
504/// // Let some time pass for the thread to be spawned.
505/// thread::sleep(Duration::from_millis(10));
506///
507/// // Ensure the thread is about to park.
508/// // This is crucial! It guarantees that the `unpark` below is not consumed
509/// // by some other code in the parked thread (e.g. inside `println!`).
510/// while !QUEUED.load(Ordering::Acquire) {
511///     // Spinning is of course inefficient; in practice, this would more likely be
512///     // a dequeue where we have no work to do if there's nobody queued.
513///     std::hint::spin_loop();
514/// }
515///
516/// // Set the flag, and let the thread wake up.
517/// // There is no race condition here: if `unpark`
518/// // happens first, `park` will return immediately.
519/// // There is also no other `park` that could consume this token,
520/// // since we waited until the other thread got queued.
521/// // Hence there is no risk of a deadlock.
522/// FLAG.store(true, Ordering::Release);
523/// println!("Unpark the thread");
524/// parked_thread.thread().unpark();
525///
526/// parked_thread.join().unwrap();
527/// ```
528///
529/// [`Thread`]: super::Thread
530/// [`unpark`]: super::Thread::unpark
531/// [`thread::park_timeout`]: park_timeout
532/// [release sequence]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release_sequence
533#[stable(feature = "rust1", since = "1.0.0")]
534pub fn park() {
535    let guard = PanicGuard;
536    // SAFETY: park_timeout is called on the parker owned by this thread.
537    unsafe {
538        current().park();
539    }
540    // No panic occurred, do not abort.
541    forget(guard);
542}
543
544/// Uses [`park_timeout`].
545///
546/// Blocks unless or until the current thread's token is made available or
547/// the specified duration has been reached (may wake spuriously).
548///
549/// The semantics of this function are equivalent to [`park`] except
550/// that the thread will be blocked for roughly no longer than `dur`. This
551/// method should not be used for precise timing due to anomalies such as
552/// preemption or platform differences that might not cause the maximum
553/// amount of time waited to be precisely `ms` long.
554///
555/// See the [park documentation][`park`] for more detail.
556#[stable(feature = "rust1", since = "1.0.0")]
557#[deprecated(since = "1.6.0", note = "replaced by `std::thread::park_timeout`")]
558pub fn park_timeout_ms(ms: u32) {
559    park_timeout(Duration::from_millis(ms as u64))
560}
561
562/// Blocks unless or until the current thread's token is made available or
563/// the specified duration has been reached (may wake spuriously).
564///
565/// The semantics of this function are equivalent to [`park`][park] except
566/// that the thread will be blocked for roughly no longer than `dur`. This
567/// method should not be used for precise timing due to anomalies such as
568/// preemption or platform differences that might not cause the maximum
569/// amount of time waited to be precisely `dur` long.
570///
571/// See the [park documentation][park] for more details.
572///
573/// # Platform-specific behavior
574///
575/// Platforms which do not support nanosecond precision for sleeping will have
576/// `dur` rounded up to the nearest granularity of time they can sleep for.
577///
578/// # Examples
579///
580/// Waiting for the complete expiration of the timeout:
581///
582/// ```rust,no_run
583/// use std::thread::park_timeout;
584/// use std::time::{Instant, Duration};
585///
586/// let timeout = Duration::from_secs(2);
587/// let beginning_park = Instant::now();
588///
589/// let mut timeout_remaining = timeout;
590/// loop {
591///     park_timeout(timeout_remaining);
592///     let elapsed = beginning_park.elapsed();
593///     if elapsed >= timeout {
594///         break;
595///     }
596///     println!("restarting park_timeout after {elapsed:?}");
597///     timeout_remaining = timeout - elapsed;
598/// }
599/// ```
600#[stable(feature = "park_timeout", since = "1.4.0")]
601pub fn park_timeout(dur: Duration) {
602    let guard = PanicGuard;
603    // SAFETY: park_timeout is called on a handle owned by this thread.
604    unsafe {
605        current().park_timeout(dur);
606    }
607    // No panic occurred, do not abort.
608    forget(guard);
609}
610
611/// Returns an estimate of the default amount of parallelism a program should use.
612///
613/// Parallelism is a resource. A given machine provides a certain capacity for
614/// parallelism, i.e., a bound on the number of computations it can perform
615/// simultaneously. This number often corresponds to the amount of CPUs a
616/// computer has, but it may diverge in various cases.
617///
618/// Host environments such as VMs or container orchestrators may want to
619/// restrict the amount of parallelism made available to programs in them. This
620/// is often done to limit the potential impact of (unintentionally)
621/// resource-intensive programs on other programs running on the same machine.
622///
623/// # Limitations
624///
625/// The purpose of this API is to provide an easy and portable way to query
626/// the default amount of parallelism the program should use. Among other things it
627/// does not expose information on NUMA regions, does not account for
628/// differences in (co)processor capabilities or current system load,
629/// and will not modify the program's global state in order to more accurately
630/// query the amount of available parallelism.
631///
632/// Where both fixed steady-state and burst limits are available the steady-state
633/// capacity will be used to ensure more predictable latencies.
634///
635/// Resource limits can be changed during the runtime of a program, therefore the value is
636/// not cached and instead recomputed every time this function is called. It should not be
637/// called from hot code.
638///
639/// The value returned by this function should be considered a simplified
640/// approximation of the actual amount of parallelism available at any given
641/// time. To get a more detailed or precise overview of the amount of
642/// parallelism available to the program, you may wish to use
643/// platform-specific APIs as well. The following platform limitations currently
644/// apply to `available_parallelism`:
645///
646/// On Windows:
647/// - It may undercount the amount of parallelism available on systems with more
648///   than 64 logical CPUs, because it reports only the logical CPUs in one
649///   processor group. Before Windows 11 and Windows Server 2022, a process was by
650///   default confined to a single processor group, so this count reflected the CPUs
651///   it could use without explicitly opting into other groups. Starting with Windows
652///   11 and Windows Server 2022, a process and its threads have affinities that by
653///   default span all processor groups, so on systems with more than 64 logical CPUs
654///   this may report fewer CPUs than are available to the program.
655/// - It may overcount the amount of parallelism available on systems limited by
656///   process-wide affinity masks, or job object limitations.
657///
658/// On Linux:
659/// - It may overcount the amount of parallelism available when limited by a
660///   process-wide affinity mask or cgroup quotas and `sched_getaffinity()` or cgroup fs can't be
661///   queried, e.g. due to sandboxing.
662/// - It may undercount the amount of parallelism if the current thread's affinity mask
663///   does not reflect the process' cpuset, e.g. due to pinned threads.
664/// - If the process is in a cgroup v1 cpu controller, this may need to
665///   scan mountpoints to find the corresponding cgroup v1 controller,
666///   which may take time on systems with large numbers of mountpoints.
667///   (This does not apply to cgroup v2, or to processes not in a
668///   cgroup.)
669/// - It does not attempt to take `ulimit` into account. If there is a limit set on the number of
670///   threads, `available_parallelism` cannot know how much of that limit a Rust program should
671///   take, or know in a reliable and race-free way how much of that limit is already taken.
672///
673/// On all targets:
674/// - It may overcount the amount of parallelism available when running in a VM
675/// with CPU usage limits (e.g. an overcommitted host).
676///
677/// # Errors
678///
679/// This function will, but is not limited to, return errors in the following
680/// cases:
681///
682/// - If the amount of parallelism is not known for the target platform.
683/// - If the program lacks permission to query the amount of parallelism made
684///   available to it.
685///
686/// # Examples
687///
688/// ```
689/// use std::thread;
690///
691/// if let Ok(count) = thread::available_parallelism() {
692///   assert!(count.get() >= 1_usize);
693/// }
694/// ```
695#[doc(alias = "available_concurrency")] // Alias for a previous name we gave this API on unstable.
696#[doc(alias = "hardware_concurrency")] // Alias for C++ `std::thread::hardware_concurrency`.
697#[doc(alias = "num_cpus")] // Alias for a popular ecosystem crate which provides similar functionality.
698#[stable(feature = "available_parallelism", since = "1.59.0")]
699pub fn available_parallelism() -> io::Result<NonZero<usize>> {
700    imp::available_parallelism()
701}