std/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 is platform-dependent and subject to change.
128//! Currently, it is 2 MiB on all Tier-1 platforms.
129//!
130//! There are two ways to manually specify the stack size for spawned threads:
131//!
132//! * Build the thread with [`Builder`] and pass the desired stack size to [`Builder::stack_size`].
133//! * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack
134//! size (in bytes). Note that setting [`Builder::stack_size`] will override this. Be aware that
135//! changes to `RUST_MIN_STACK` may be ignored after program start.
136//!
137//! Note that the stack size of the main thread is *not* determined by Rust.
138//!
139//! [channels]: crate::sync::mpsc
140//! [`join`]: JoinHandle::join
141//! [`Result`]: crate::result::Result
142//! [`Ok`]: crate::result::Result::Ok
143//! [`Err`]: crate::result::Result::Err
144//! [`thread::current`]: current::current
145//! [`thread::Result`]: Result
146//! [`unpark`]: Thread::unpark
147//! [`thread::park_timeout`]: park_timeout
148//! [`Cell`]: crate::cell::Cell
149//! [`RefCell`]: crate::cell::RefCell
150//! [`with`]: LocalKey::with
151//! [`thread_local!`]: crate::thread_local
152
153#![stable(feature = "rust1", since = "1.0.0")]
154#![deny(unsafe_op_in_unsafe_fn)]
155// Under `test`, `__FastLocalKeyInner` seems unused.
156#![cfg_attr(test, allow(dead_code))]
157
158#[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))]
159mod tests;
160
161use crate::any::Any;
162use crate::cell::UnsafeCell;
163use crate::ffi::CStr;
164use crate::marker::PhantomData;
165use crate::mem::{self, ManuallyDrop, forget};
166use crate::num::NonZero;
167use crate::pin::Pin;
168use crate::sync::Arc;
169use crate::sync::atomic::{Atomic, AtomicUsize, Ordering};
170use crate::sys::sync::Parker;
171use crate::sys::thread as imp;
172use crate::sys_common::{AsInner, IntoInner};
173use crate::time::{Duration, Instant};
174use crate::{env, fmt, io, panic, panicking, str};
175
176#[stable(feature = "scoped_threads", since = "1.63.0")]
177mod scoped;
178
179#[stable(feature = "scoped_threads", since = "1.63.0")]
180pub use scoped::{Scope, ScopedJoinHandle, scope};
181
182mod current;
183
184#[stable(feature = "rust1", since = "1.0.0")]
185pub use current::current;
186pub(crate) use current::{current_id, current_or_unnamed, current_os_id, drop_current};
187use current::{set_current, try_with_current};
188
189mod spawnhook;
190
191#[unstable(feature = "thread_spawn_hook", issue = "132951")]
192pub use spawnhook::add_spawn_hook;
193
194////////////////////////////////////////////////////////////////////////////////
195// Thread-local storage
196////////////////////////////////////////////////////////////////////////////////
197
198#[macro_use]
199mod local;
200
201#[stable(feature = "rust1", since = "1.0.0")]
202pub use self::local::{AccessError, LocalKey};
203
204// Implementation details used by the thread_local!{} macro.
205#[doc(hidden)]
206#[unstable(feature = "thread_local_internals", issue = "none")]
207pub mod local_impl {
208 pub use crate::sys::thread_local::*;
209}
210
211////////////////////////////////////////////////////////////////////////////////
212// Builder
213////////////////////////////////////////////////////////////////////////////////
214
215/// Thread factory, which can be used in order to configure the properties of
216/// a new thread.
217///
218/// Methods can be chained on it in order to configure it.
219///
220/// The two configurations available are:
221///
222/// - [`name`]: specifies an [associated name for the thread][naming-threads]
223/// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
224///
225/// The [`spawn`] method will take ownership of the builder and create an
226/// [`io::Result`] to the thread handle with the given configuration.
227///
228/// The [`thread::spawn`] free function uses a `Builder` with default
229/// configuration and [`unwrap`]s its return value.
230///
231/// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
232/// to recover from a failure to launch a thread, indeed the free function will
233/// panic where the `Builder` method will return a [`io::Result`].
234///
235/// # Examples
236///
237/// ```
238/// use std::thread;
239///
240/// let builder = thread::Builder::new();
241///
242/// let handler = builder.spawn(|| {
243/// // thread code
244/// }).unwrap();
245///
246/// handler.join().unwrap();
247/// ```
248///
249/// [`stack_size`]: Builder::stack_size
250/// [`name`]: Builder::name
251/// [`spawn`]: Builder::spawn
252/// [`thread::spawn`]: spawn
253/// [`io::Result`]: crate::io::Result
254/// [`unwrap`]: crate::result::Result::unwrap
255/// [naming-threads]: ./index.html#naming-threads
256/// [stack-size]: ./index.html#stack-size
257#[must_use = "must eventually spawn the thread"]
258#[stable(feature = "rust1", since = "1.0.0")]
259#[derive(Debug)]
260pub struct Builder {
261 // A name for the thread-to-be, for identification in panic messages
262 name: Option<String>,
263 // The size of the stack for the spawned thread in bytes
264 stack_size: Option<usize>,
265 // Skip running and inheriting the thread spawn hooks
266 no_hooks: bool,
267}
268
269impl Builder {
270 /// Generates the base configuration for spawning a thread, from which
271 /// configuration methods can be chained.
272 ///
273 /// # Examples
274 ///
275 /// ```
276 /// use std::thread;
277 ///
278 /// let builder = thread::Builder::new()
279 /// .name("foo".into())
280 /// .stack_size(32 * 1024);
281 ///
282 /// let handler = builder.spawn(|| {
283 /// // thread code
284 /// }).unwrap();
285 ///
286 /// handler.join().unwrap();
287 /// ```
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn new() -> Builder {
290 Builder { name: None, stack_size: None, no_hooks: false }
291 }
292
293 /// Names the thread-to-be. Currently the name is used for identification
294 /// only in panic messages.
295 ///
296 /// The name must not contain null bytes (`\0`).
297 ///
298 /// For more information about named threads, see
299 /// [this module-level documentation][naming-threads].
300 ///
301 /// # Examples
302 ///
303 /// ```
304 /// use std::thread;
305 ///
306 /// let builder = thread::Builder::new()
307 /// .name("foo".into());
308 ///
309 /// let handler = builder.spawn(|| {
310 /// assert_eq!(thread::current().name(), Some("foo"))
311 /// }).unwrap();
312 ///
313 /// handler.join().unwrap();
314 /// ```
315 ///
316 /// [naming-threads]: ./index.html#naming-threads
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub fn name(mut self, name: String) -> Builder {
319 self.name = Some(name);
320 self
321 }
322
323 /// Sets the size of the stack (in bytes) for the new thread.
324 ///
325 /// The actual stack size may be greater than this value if
326 /// the platform specifies a minimal stack size.
327 ///
328 /// For more information about the stack size for threads, see
329 /// [this module-level documentation][stack-size].
330 ///
331 /// # Examples
332 ///
333 /// ```
334 /// use std::thread;
335 ///
336 /// let builder = thread::Builder::new().stack_size(32 * 1024);
337 /// ```
338 ///
339 /// [stack-size]: ./index.html#stack-size
340 #[stable(feature = "rust1", since = "1.0.0")]
341 pub fn stack_size(mut self, size: usize) -> Builder {
342 self.stack_size = Some(size);
343 self
344 }
345
346 /// Disables running and inheriting [spawn hooks](add_spawn_hook).
347 ///
348 /// Use this if the parent thread is in no way relevant for the child thread.
349 /// For example, when lazily spawning threads for a thread pool.
350 #[unstable(feature = "thread_spawn_hook", issue = "132951")]
351 pub fn no_hooks(mut self) -> Builder {
352 self.no_hooks = true;
353 self
354 }
355
356 /// Spawns a new thread by taking ownership of the `Builder`, and returns an
357 /// [`io::Result`] to its [`JoinHandle`].
358 ///
359 /// The spawned thread may outlive the caller (unless the caller thread
360 /// is the main thread; the whole process is terminated when the main
361 /// thread finishes). The join handle can be used to block on
362 /// termination of the spawned thread, including recovering its panics.
363 ///
364 /// For a more complete documentation see [`thread::spawn`][`spawn`].
365 ///
366 /// # Errors
367 ///
368 /// Unlike the [`spawn`] free function, this method yields an
369 /// [`io::Result`] to capture any failure to create the thread at
370 /// the OS level.
371 ///
372 /// [`io::Result`]: crate::io::Result
373 ///
374 /// # Panics
375 ///
376 /// Panics if a thread name was set and it contained null bytes.
377 ///
378 /// # Examples
379 ///
380 /// ```
381 /// use std::thread;
382 ///
383 /// let builder = thread::Builder::new();
384 ///
385 /// let handler = builder.spawn(|| {
386 /// // thread code
387 /// }).unwrap();
388 ///
389 /// handler.join().unwrap();
390 /// ```
391 #[stable(feature = "rust1", since = "1.0.0")]
392 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
393 pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
394 where
395 F: FnOnce() -> T,
396 F: Send + 'static,
397 T: Send + 'static,
398 {
399 unsafe { self.spawn_unchecked(f) }
400 }
401
402 /// Spawns a new thread without any lifetime restrictions by taking ownership
403 /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
404 ///
405 /// The spawned thread may outlive the caller (unless the caller thread
406 /// is the main thread; the whole process is terminated when the main
407 /// thread finishes). The join handle can be used to block on
408 /// termination of the spawned thread, including recovering its panics.
409 ///
410 /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
411 /// except for the relaxed lifetime bounds, which render it unsafe.
412 /// For a more complete documentation see [`thread::spawn`][`spawn`].
413 ///
414 /// # Errors
415 ///
416 /// Unlike the [`spawn`] free function, this method yields an
417 /// [`io::Result`] to capture any failure to create the thread at
418 /// the OS level.
419 ///
420 /// # Panics
421 ///
422 /// Panics if a thread name was set and it contained null bytes.
423 ///
424 /// # Safety
425 ///
426 /// The caller has to ensure that the spawned thread does not outlive any
427 /// references in the supplied thread closure and its return type.
428 /// This can be guaranteed in two ways:
429 ///
430 /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
431 /// data is dropped
432 /// - use only types with `'static` lifetime bounds, i.e., those with no or only
433 /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
434 /// and [`thread::spawn`][`spawn`] enforce this property statically)
435 ///
436 /// # Examples
437 ///
438 /// ```
439 /// use std::thread;
440 ///
441 /// let builder = thread::Builder::new();
442 ///
443 /// let x = 1;
444 /// let thread_x = &x;
445 ///
446 /// let handler = unsafe {
447 /// builder.spawn_unchecked(move || {
448 /// println!("x = {}", *thread_x);
449 /// }).unwrap()
450 /// };
451 ///
452 /// // caller has to ensure `join()` is called, otherwise
453 /// // it is possible to access freed memory if `x` gets
454 /// // dropped before the thread closure is executed!
455 /// handler.join().unwrap();
456 /// ```
457 ///
458 /// [`io::Result`]: crate::io::Result
459 #[stable(feature = "thread_spawn_unchecked", since = "1.82.0")]
460 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
461 pub unsafe fn spawn_unchecked<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
462 where
463 F: FnOnce() -> T,
464 F: Send,
465 T: Send,
466 {
467 Ok(JoinHandle(unsafe { self.spawn_unchecked_(f, None) }?))
468 }
469
470 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
471 unsafe fn spawn_unchecked_<'scope, F, T>(
472 self,
473 f: F,
474 scope_data: Option<Arc<scoped::ScopeData>>,
475 ) -> io::Result<JoinInner<'scope, T>>
476 where
477 F: FnOnce() -> T,
478 F: Send,
479 T: Send,
480 {
481 let Builder { name, stack_size, no_hooks } = self;
482
483 let stack_size = stack_size.unwrap_or_else(|| {
484 static MIN: Atomic<usize> = AtomicUsize::new(0);
485
486 match MIN.load(Ordering::Relaxed) {
487 0 => {}
488 n => return n - 1,
489 }
490
491 let amt = env::var_os("RUST_MIN_STACK")
492 .and_then(|s| s.to_str().and_then(|s| s.parse().ok()))
493 .unwrap_or(imp::DEFAULT_MIN_STACK_SIZE);
494
495 // 0 is our sentinel value, so ensure that we'll never see 0 after
496 // initialization has run
497 MIN.store(amt + 1, Ordering::Relaxed);
498 amt
499 });
500
501 let id = ThreadId::new();
502 let my_thread = Thread::new(id, name);
503
504 let hooks = if no_hooks {
505 spawnhook::ChildSpawnHooks::default()
506 } else {
507 spawnhook::run_spawn_hooks(&my_thread)
508 };
509
510 let their_thread = my_thread.clone();
511
512 let my_packet: Arc<Packet<'scope, T>> = Arc::new(Packet {
513 scope: scope_data,
514 result: UnsafeCell::new(None),
515 _marker: PhantomData,
516 });
517 let their_packet = my_packet.clone();
518
519 // Pass `f` in `MaybeUninit` because actually that closure might *run longer than the lifetime of `F`*.
520 // See <https://github.com/rust-lang/rust/issues/101983> for more details.
521 // To prevent leaks we use a wrapper that drops its contents.
522 #[repr(transparent)]
523 struct MaybeDangling<T>(mem::MaybeUninit<T>);
524 impl<T> MaybeDangling<T> {
525 fn new(x: T) -> Self {
526 MaybeDangling(mem::MaybeUninit::new(x))
527 }
528 fn into_inner(self) -> T {
529 // Make sure we don't drop.
530 let this = ManuallyDrop::new(self);
531 // SAFETY: we are always initialized.
532 unsafe { this.0.assume_init_read() }
533 }
534 }
535 impl<T> Drop for MaybeDangling<T> {
536 fn drop(&mut self) {
537 // SAFETY: we are always initialized.
538 unsafe { self.0.assume_init_drop() };
539 }
540 }
541
542 let f = MaybeDangling::new(f);
543 let main = move || {
544 if let Err(_thread) = set_current(their_thread.clone()) {
545 // Both the current thread handle and the ID should not be
546 // initialized yet. Since only the C runtime and some of our
547 // platform code run before this, this point shouldn't be
548 // reachable. Use an abort to save binary size (see #123356).
549 rtabort!("something here is badly broken!");
550 }
551
552 if let Some(name) = their_thread.cname() {
553 imp::Thread::set_name(name);
554 }
555
556 let f = f.into_inner();
557 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
558 crate::sys::backtrace::__rust_begin_short_backtrace(|| hooks.run());
559 crate::sys::backtrace::__rust_begin_short_backtrace(f)
560 }));
561 // SAFETY: `their_packet` as been built just above and moved by the
562 // closure (it is an Arc<...>) and `my_packet` will be stored in the
563 // same `JoinInner` as this closure meaning the mutation will be
564 // safe (not modify it and affect a value far away).
565 unsafe { *their_packet.result.get() = Some(try_result) };
566 // Here `their_packet` gets dropped, and if this is the last `Arc` for that packet that
567 // will call `decrement_num_running_threads` and therefore signal that this thread is
568 // done.
569 drop(their_packet);
570 // Here, the lifetime `'scope` can end. `main` keeps running for a bit
571 // after that before returning itself.
572 };
573
574 if let Some(scope_data) = &my_packet.scope {
575 scope_data.increment_num_running_threads();
576 }
577
578 let main = Box::new(main);
579 // SAFETY: dynamic size and alignment of the Box remain the same. See below for why the
580 // lifetime change is justified.
581 let main =
582 unsafe { Box::from_raw(Box::into_raw(main) as *mut (dyn FnOnce() + Send + 'static)) };
583
584 Ok(JoinInner {
585 // SAFETY:
586 //
587 // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
588 // through FFI or otherwise used with low-level threading primitives that have no
589 // notion of or way to enforce lifetimes.
590 //
591 // As mentioned in the `Safety` section of this function's documentation, the caller of
592 // this function needs to guarantee that the passed-in lifetime is sufficiently long
593 // for the lifetime of the thread.
594 //
595 // Similarly, the `sys` implementation must guarantee that no references to the closure
596 // exist after the thread has terminated, which is signaled by `Thread::join`
597 // returning.
598 native: unsafe { imp::Thread::new(stack_size, my_thread.name(), main)? },
599 thread: my_thread,
600 packet: my_packet,
601 })
602 }
603}
604
605////////////////////////////////////////////////////////////////////////////////
606// Free functions
607////////////////////////////////////////////////////////////////////////////////
608
609/// Spawns a new thread, returning a [`JoinHandle`] for it.
610///
611/// The join handle provides a [`join`] method that can be used to join the spawned
612/// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
613/// the argument given to [`panic!`].
614///
615/// If the join handle is dropped, the spawned thread will implicitly be *detached*.
616/// In this case, the spawned thread may no longer be joined.
617/// (It is the responsibility of the program to either eventually join threads it
618/// creates or detach them; otherwise, a resource leak will result.)
619///
620/// This call will create a thread using default parameters of [`Builder`], if you
621/// want to specify the stack size or the name of the thread, use this API
622/// instead.
623///
624/// As you can see in the signature of `spawn` there are two constraints on
625/// both the closure given to `spawn` and its return value, let's explain them:
626///
627/// - The `'static` constraint means that the closure and its return value
628/// must have a lifetime of the whole program execution. The reason for this
629/// is that threads can outlive the lifetime they have been created in.
630///
631/// Indeed if the thread, and by extension its return value, can outlive their
632/// caller, we need to make sure that they will be valid afterwards, and since
633/// we *can't* know when it will return we need to have them valid as long as
634/// possible, that is until the end of the program, hence the `'static`
635/// lifetime.
636/// - The [`Send`] constraint is because the closure will need to be passed
637/// *by value* from the thread where it is spawned to the new thread. Its
638/// return value will need to be passed from the new thread to the thread
639/// where it is `join`ed.
640/// As a reminder, the [`Send`] marker trait expresses that it is safe to be
641/// passed from thread to thread. [`Sync`] expresses that it is safe to have a
642/// reference be passed from thread to thread.
643///
644/// # Panics
645///
646/// Panics if the OS fails to create a thread; use [`Builder::spawn`]
647/// to recover from such errors.
648///
649/// # Examples
650///
651/// Creating a thread.
652///
653/// ```
654/// use std::thread;
655///
656/// let handler = thread::spawn(|| {
657/// // thread code
658/// });
659///
660/// handler.join().unwrap();
661/// ```
662///
663/// As mentioned in the module documentation, threads are usually made to
664/// communicate using [`channels`], here is how it usually looks.
665///
666/// This example also shows how to use `move`, in order to give ownership
667/// of values to a thread.
668///
669/// ```
670/// use std::thread;
671/// use std::sync::mpsc::channel;
672///
673/// let (tx, rx) = channel();
674///
675/// let sender = thread::spawn(move || {
676/// tx.send("Hello, thread".to_owned())
677/// .expect("Unable to send on channel");
678/// });
679///
680/// let receiver = thread::spawn(move || {
681/// let value = rx.recv().expect("Unable to receive from channel");
682/// println!("{value}");
683/// });
684///
685/// sender.join().expect("The sender thread has panicked");
686/// receiver.join().expect("The receiver thread has panicked");
687/// ```
688///
689/// A thread can also return a value through its [`JoinHandle`], you can use
690/// this to make asynchronous computations (futures might be more appropriate
691/// though).
692///
693/// ```
694/// use std::thread;
695///
696/// let computation = thread::spawn(|| {
697/// // Some expensive computation.
698/// 42
699/// });
700///
701/// let result = computation.join().unwrap();
702/// println!("{result}");
703/// ```
704///
705/// # Notes
706///
707/// This function has the same minimal guarantee regarding "foreign" unwinding operations (e.g.
708/// an exception thrown from C++ code, or a `panic!` in Rust code compiled or linked with a
709/// different runtime) as [`catch_unwind`]; namely, if the thread created with `thread::spawn`
710/// unwinds all the way to the root with such an exception, one of two behaviors are possible,
711/// and it is unspecified which will occur:
712///
713/// * The process aborts.
714/// * The process does not abort, and [`join`] will return a `Result::Err`
715/// containing an opaque type.
716///
717/// [`catch_unwind`]: ../../std/panic/fn.catch_unwind.html
718/// [`channels`]: crate::sync::mpsc
719/// [`join`]: JoinHandle::join
720/// [`Err`]: crate::result::Result::Err
721#[stable(feature = "rust1", since = "1.0.0")]
722#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
723pub fn spawn<F, T>(f: F) -> JoinHandle<T>
724where
725 F: FnOnce() -> T,
726 F: Send + 'static,
727 T: Send + 'static,
728{
729 Builder::new().spawn(f).expect("failed to spawn thread")
730}
731
732/// Cooperatively gives up a timeslice to the OS scheduler.
733///
734/// This calls the underlying OS scheduler's yield primitive, signaling
735/// that the calling thread is willing to give up its remaining timeslice
736/// so that the OS may schedule other threads on the CPU.
737///
738/// A drawback of yielding in a loop is that if the OS does not have any
739/// other ready threads to run on the current CPU, the thread will effectively
740/// busy-wait, which wastes CPU time and energy.
741///
742/// Therefore, when waiting for events of interest, a programmer's first
743/// choice should be to use synchronization devices such as [`channel`]s,
744/// [`Condvar`]s, [`Mutex`]es or [`join`] since these primitives are
745/// implemented in a blocking manner, giving up the CPU until the event
746/// of interest has occurred which avoids repeated yielding.
747///
748/// `yield_now` should thus be used only rarely, mostly in situations where
749/// repeated polling is required because there is no other suitable way to
750/// learn when an event of interest has occurred.
751///
752/// # Examples
753///
754/// ```
755/// use std::thread;
756///
757/// thread::yield_now();
758/// ```
759///
760/// [`channel`]: crate::sync::mpsc
761/// [`join`]: JoinHandle::join
762/// [`Condvar`]: crate::sync::Condvar
763/// [`Mutex`]: crate::sync::Mutex
764#[stable(feature = "rust1", since = "1.0.0")]
765pub fn yield_now() {
766 imp::Thread::yield_now()
767}
768
769/// Determines whether the current thread is unwinding because of panic.
770///
771/// A common use of this feature is to poison shared resources when writing
772/// unsafe code, by checking `panicking` when the `drop` is called.
773///
774/// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
775/// already poison themselves when a thread panics while holding the lock.
776///
777/// This can also be used in multithreaded applications, in order to send a
778/// message to other threads warning that a thread has panicked (e.g., for
779/// monitoring purposes).
780///
781/// # Examples
782///
783/// ```should_panic
784/// use std::thread;
785///
786/// struct SomeStruct;
787///
788/// impl Drop for SomeStruct {
789/// fn drop(&mut self) {
790/// if thread::panicking() {
791/// println!("dropped while unwinding");
792/// } else {
793/// println!("dropped while not unwinding");
794/// }
795/// }
796/// }
797///
798/// {
799/// print!("a: ");
800/// let a = SomeStruct;
801/// }
802///
803/// {
804/// print!("b: ");
805/// let b = SomeStruct;
806/// panic!()
807/// }
808/// ```
809///
810/// [Mutex]: crate::sync::Mutex
811#[inline]
812#[must_use]
813#[stable(feature = "rust1", since = "1.0.0")]
814pub fn panicking() -> bool {
815 panicking::panicking()
816}
817
818/// Uses [`sleep`].
819///
820/// Puts the current thread to sleep for at least the specified amount of time.
821///
822/// The thread may sleep longer than the duration specified due to scheduling
823/// specifics or platform-dependent functionality. It will never sleep less.
824///
825/// This function is blocking, and should not be used in `async` functions.
826///
827/// # Platform-specific behavior
828///
829/// On Unix platforms, the underlying syscall may be interrupted by a
830/// spurious wakeup or signal handler. To ensure the sleep occurs for at least
831/// the specified duration, this function may invoke that system call multiple
832/// times.
833///
834/// # Examples
835///
836/// ```no_run
837/// use std::thread;
838///
839/// // Let's sleep for 2 seconds:
840/// thread::sleep_ms(2000);
841/// ```
842#[stable(feature = "rust1", since = "1.0.0")]
843#[deprecated(since = "1.6.0", note = "replaced by `std::thread::sleep`")]
844pub fn sleep_ms(ms: u32) {
845 sleep(Duration::from_millis(ms as u64))
846}
847
848/// Puts the current thread to sleep for at least the specified amount of time.
849///
850/// The thread may sleep longer than the duration specified due to scheduling
851/// specifics or platform-dependent functionality. It will never sleep less.
852///
853/// This function is blocking, and should not be used in `async` functions.
854///
855/// # Platform-specific behavior
856///
857/// On Unix platforms, the underlying syscall may be interrupted by a
858/// spurious wakeup or signal handler. To ensure the sleep occurs for at least
859/// the specified duration, this function may invoke that system call multiple
860/// times.
861/// Platforms which do not support nanosecond precision for sleeping will
862/// have `dur` rounded up to the nearest granularity of time they can sleep for.
863///
864/// Currently, specifying a zero duration on Unix platforms returns immediately
865/// without invoking the underlying [`nanosleep`] syscall, whereas on Windows
866/// platforms the underlying [`Sleep`] syscall is always invoked.
867/// If the intention is to yield the current time-slice you may want to use
868/// [`yield_now`] instead.
869///
870/// [`nanosleep`]: https://linux.die.net/man/2/nanosleep
871/// [`Sleep`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
872///
873/// # Examples
874///
875/// ```no_run
876/// use std::{thread, time};
877///
878/// let ten_millis = time::Duration::from_millis(10);
879/// let now = time::Instant::now();
880///
881/// thread::sleep(ten_millis);
882///
883/// assert!(now.elapsed() >= ten_millis);
884/// ```
885#[stable(feature = "thread_sleep", since = "1.4.0")]
886pub fn sleep(dur: Duration) {
887 imp::Thread::sleep(dur)
888}
889
890/// Puts the current thread to sleep until the specified deadline has passed.
891///
892/// The thread may still be asleep after the deadline specified due to
893/// scheduling specifics or platform-dependent functionality. It will never
894/// wake before.
895///
896/// This function is blocking, and should not be used in `async` functions.
897///
898/// # Platform-specific behavior
899///
900/// In most cases this function will call an OS specific function. Where that
901/// is not supported [`sleep`] is used. Those platforms are referred to as other
902/// in the table below.
903///
904/// # Underlying System calls
905///
906/// The following system calls are [currently] being used:
907///
908/// | Platform | System call |
909/// |-----------|----------------------------------------------------------------------|
910/// | Linux | [clock_nanosleep] (Monotonic clock) |
911/// | BSD except OpenBSD | [clock_nanosleep] (Monotonic Clock)] |
912/// | Android | [clock_nanosleep] (Monotonic Clock)] |
913/// | Solaris | [clock_nanosleep] (Monotonic Clock)] |
914/// | Illumos | [clock_nanosleep] (Monotonic Clock)] |
915/// | Dragonfly | [clock_nanosleep] (Monotonic Clock)] |
916/// | Hurd | [clock_nanosleep] (Monotonic Clock)] |
917/// | Fuchsia | [clock_nanosleep] (Monotonic Clock)] |
918/// | Vxworks | [clock_nanosleep] (Monotonic Clock)] |
919/// | Other | `sleep_until` uses [`sleep`] and does not issue a syscall itself |
920///
921/// [currently]: crate::io#platform-specific-behavior
922/// [clock_nanosleep]: https://linux.die.net/man/3/clock_nanosleep
923///
924/// **Disclaimer:** These system calls might change over time.
925///
926/// # Examples
927///
928/// A simple game loop that limits the game to 60 frames per second.
929///
930/// ```no_run
931/// #![feature(thread_sleep_until)]
932/// # use std::time::{Duration, Instant};
933/// # use std::thread;
934/// #
935/// # fn update() {}
936/// # fn render() {}
937/// #
938/// let max_fps = 60.0;
939/// let frame_time = Duration::from_secs_f32(1.0/max_fps);
940/// let mut next_frame = Instant::now();
941/// loop {
942/// thread::sleep_until(next_frame);
943/// next_frame += frame_time;
944/// update();
945/// render();
946/// }
947/// ```
948///
949/// A slow API we must not call too fast and which takes a few
950/// tries before succeeding. By using `sleep_until` the time the
951/// API call takes does not influence when we retry or when we give up
952///
953/// ```no_run
954/// #![feature(thread_sleep_until)]
955/// # use std::time::{Duration, Instant};
956/// # use std::thread;
957/// #
958/// # enum Status {
959/// # Ready(usize),
960/// # Waiting,
961/// # }
962/// # fn slow_web_api_call() -> Status { Status::Ready(42) }
963/// #
964/// # const MAX_DURATION: Duration = Duration::from_secs(10);
965/// #
966/// # fn try_api_call() -> Result<usize, ()> {
967/// let deadline = Instant::now() + MAX_DURATION;
968/// let delay = Duration::from_millis(250);
969/// let mut next_attempt = Instant::now();
970/// loop {
971/// if Instant::now() > deadline {
972/// break Err(());
973/// }
974/// if let Status::Ready(data) = slow_web_api_call() {
975/// break Ok(data);
976/// }
977///
978/// next_attempt = deadline.min(next_attempt + delay);
979/// thread::sleep_until(next_attempt);
980/// }
981/// # }
982/// # let _data = try_api_call();
983/// ```
984#[unstable(feature = "thread_sleep_until", issue = "113752")]
985pub fn sleep_until(deadline: Instant) {
986 imp::Thread::sleep_until(deadline)
987}
988
989/// Used to ensure that `park` and `park_timeout` do not unwind, as that can
990/// cause undefined behavior if not handled correctly (see #102398 for context).
991struct PanicGuard;
992
993impl Drop for PanicGuard {
994 fn drop(&mut self) {
995 rtabort!("an irrecoverable error occurred while synchronizing threads")
996 }
997}
998
999/// Blocks unless or until the current thread's token is made available.
1000///
1001/// A call to `park` does not guarantee that the thread will remain parked
1002/// forever, and callers should be prepared for this possibility. However,
1003/// it is guaranteed that this function will not panic (it may abort the
1004/// process if the implementation encounters some rare errors).
1005///
1006/// # `park` and `unpark`
1007///
1008/// Every thread is equipped with some basic low-level blocking support, via the
1009/// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
1010/// method. [`park`] blocks the current thread, which can then be resumed from
1011/// another thread by calling the [`unpark`] method on the blocked thread's
1012/// handle.
1013///
1014/// Conceptually, each [`Thread`] handle has an associated token, which is
1015/// initially not present:
1016///
1017/// * The [`thread::park`][`park`] function blocks the current thread unless or
1018/// until the token is available for its thread handle, at which point it
1019/// atomically consumes the token. It may also return *spuriously*, without
1020/// consuming the token. [`thread::park_timeout`] does the same, but allows
1021/// specifying a maximum time to block the thread for.
1022///
1023/// * The [`unpark`] method on a [`Thread`] atomically makes the token available
1024/// if it wasn't already. Because the token is initially absent, [`unpark`]
1025/// followed by [`park`] will result in the second call returning immediately.
1026///
1027/// The API is typically used by acquiring a handle to the current thread,
1028/// placing that handle in a shared data structure so that other threads can
1029/// find it, and then `park`ing in a loop. When some desired condition is met, another
1030/// thread calls [`unpark`] on the handle.
1031///
1032/// The motivation for this design is twofold:
1033///
1034/// * It avoids the need to allocate mutexes and condvars when building new
1035/// synchronization primitives; the threads already provide basic
1036/// blocking/signaling.
1037///
1038/// * It can be implemented very efficiently on many platforms.
1039///
1040/// # Memory Ordering
1041///
1042/// Calls to `unpark` _synchronize-with_ calls to `park`, meaning that memory
1043/// operations performed before a call to `unpark` are made visible to the thread that
1044/// consumes the token and returns from `park`. Note that all `park` and `unpark`
1045/// operations for a given thread form a total order and _all_ prior `unpark` operations
1046/// synchronize-with `park`.
1047///
1048/// In atomic ordering terms, `unpark` performs a `Release` operation and `park`
1049/// performs the corresponding `Acquire` operation. Calls to `unpark` for the same
1050/// thread form a [release sequence].
1051///
1052/// Note that being unblocked does not imply a call was made to `unpark`, because
1053/// wakeups can also be spurious. For example, a valid, but inefficient,
1054/// implementation could have `park` and `unpark` return immediately without doing anything,
1055/// making *all* wakeups spurious.
1056///
1057/// # Examples
1058///
1059/// ```
1060/// use std::thread;
1061/// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
1062/// use std::time::Duration;
1063///
1064/// let flag = Arc::new(AtomicBool::new(false));
1065/// let flag2 = Arc::clone(&flag);
1066///
1067/// let parked_thread = thread::spawn(move || {
1068/// // We want to wait until the flag is set. We *could* just spin, but using
1069/// // park/unpark is more efficient.
1070/// while !flag2.load(Ordering::Relaxed) {
1071/// println!("Parking thread");
1072/// thread::park();
1073/// // We *could* get here spuriously, i.e., way before the 10ms below are over!
1074/// // But that is no problem, we are in a loop until the flag is set anyway.
1075/// println!("Thread unparked");
1076/// }
1077/// println!("Flag received");
1078/// });
1079///
1080/// // Let some time pass for the thread to be spawned.
1081/// thread::sleep(Duration::from_millis(10));
1082///
1083/// // Set the flag, and let the thread wake up.
1084/// // There is no race condition here, if `unpark`
1085/// // happens first, `park` will return immediately.
1086/// // Hence there is no risk of a deadlock.
1087/// flag.store(true, Ordering::Relaxed);
1088/// println!("Unpark the thread");
1089/// parked_thread.thread().unpark();
1090///
1091/// parked_thread.join().unwrap();
1092/// ```
1093///
1094/// [`unpark`]: Thread::unpark
1095/// [`thread::park_timeout`]: park_timeout
1096/// [release sequence]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release_sequence
1097#[stable(feature = "rust1", since = "1.0.0")]
1098pub fn park() {
1099 let guard = PanicGuard;
1100 // SAFETY: park_timeout is called on the parker owned by this thread.
1101 unsafe {
1102 current().park();
1103 }
1104 // No panic occurred, do not abort.
1105 forget(guard);
1106}
1107
1108/// Uses [`park_timeout`].
1109///
1110/// Blocks unless or until the current thread's token is made available or
1111/// the specified duration has been reached (may wake spuriously).
1112///
1113/// The semantics of this function are equivalent to [`park`] except
1114/// that the thread will be blocked for roughly no longer than `dur`. This
1115/// method should not be used for precise timing due to anomalies such as
1116/// preemption or platform differences that might not cause the maximum
1117/// amount of time waited to be precisely `ms` long.
1118///
1119/// See the [park documentation][`park`] for more detail.
1120#[stable(feature = "rust1", since = "1.0.0")]
1121#[deprecated(since = "1.6.0", note = "replaced by `std::thread::park_timeout`")]
1122pub fn park_timeout_ms(ms: u32) {
1123 park_timeout(Duration::from_millis(ms as u64))
1124}
1125
1126/// Blocks unless or until the current thread's token is made available or
1127/// the specified duration has been reached (may wake spuriously).
1128///
1129/// The semantics of this function are equivalent to [`park`][park] except
1130/// that the thread will be blocked for roughly no longer than `dur`. This
1131/// method should not be used for precise timing due to anomalies such as
1132/// preemption or platform differences that might not cause the maximum
1133/// amount of time waited to be precisely `dur` long.
1134///
1135/// See the [park documentation][park] for more details.
1136///
1137/// # Platform-specific behavior
1138///
1139/// Platforms which do not support nanosecond precision for sleeping will have
1140/// `dur` rounded up to the nearest granularity of time they can sleep for.
1141///
1142/// # Examples
1143///
1144/// Waiting for the complete expiration of the timeout:
1145///
1146/// ```rust,no_run
1147/// use std::thread::park_timeout;
1148/// use std::time::{Instant, Duration};
1149///
1150/// let timeout = Duration::from_secs(2);
1151/// let beginning_park = Instant::now();
1152///
1153/// let mut timeout_remaining = timeout;
1154/// loop {
1155/// park_timeout(timeout_remaining);
1156/// let elapsed = beginning_park.elapsed();
1157/// if elapsed >= timeout {
1158/// break;
1159/// }
1160/// println!("restarting park_timeout after {elapsed:?}");
1161/// timeout_remaining = timeout - elapsed;
1162/// }
1163/// ```
1164#[stable(feature = "park_timeout", since = "1.4.0")]
1165pub fn park_timeout(dur: Duration) {
1166 let guard = PanicGuard;
1167 // SAFETY: park_timeout is called on a handle owned by this thread.
1168 unsafe {
1169 current().park_timeout(dur);
1170 }
1171 // No panic occurred, do not abort.
1172 forget(guard);
1173}
1174
1175////////////////////////////////////////////////////////////////////////////////
1176// ThreadId
1177////////////////////////////////////////////////////////////////////////////////
1178
1179/// A unique identifier for a running thread.
1180///
1181/// A `ThreadId` is an opaque object that uniquely identifies each thread
1182/// created during the lifetime of a process. `ThreadId`s are guaranteed not to
1183/// be reused, even when a thread terminates. `ThreadId`s are under the control
1184/// of Rust's standard library and there may not be any relationship between
1185/// `ThreadId` and the underlying platform's notion of a thread identifier --
1186/// the two concepts cannot, therefore, be used interchangeably. A `ThreadId`
1187/// can be retrieved from the [`id`] method on a [`Thread`].
1188///
1189/// # Examples
1190///
1191/// ```
1192/// use std::thread;
1193///
1194/// let other_thread = thread::spawn(|| {
1195/// thread::current().id()
1196/// });
1197///
1198/// let other_thread_id = other_thread.join().unwrap();
1199/// assert!(thread::current().id() != other_thread_id);
1200/// ```
1201///
1202/// [`id`]: Thread::id
1203#[stable(feature = "thread_id", since = "1.19.0")]
1204#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1205pub struct ThreadId(NonZero<u64>);
1206
1207impl ThreadId {
1208 // Generate a new unique thread ID.
1209 pub(crate) fn new() -> ThreadId {
1210 #[cold]
1211 fn exhausted() -> ! {
1212 panic!("failed to generate unique thread ID: bitspace exhausted")
1213 }
1214
1215 cfg_select! {
1216 target_has_atomic = "64" => {
1217 use crate::sync::atomic::{Atomic, AtomicU64};
1218
1219 static COUNTER: Atomic<u64> = AtomicU64::new(0);
1220
1221 let mut last = COUNTER.load(Ordering::Relaxed);
1222 loop {
1223 let Some(id) = last.checked_add(1) else {
1224 exhausted();
1225 };
1226
1227 match COUNTER.compare_exchange_weak(last, id, Ordering::Relaxed, Ordering::Relaxed) {
1228 Ok(_) => return ThreadId(NonZero::new(id).unwrap()),
1229 Err(id) => last = id,
1230 }
1231 }
1232 }
1233 _ => {
1234 use crate::sync::{Mutex, PoisonError};
1235
1236 static COUNTER: Mutex<u64> = Mutex::new(0);
1237
1238 let mut counter = COUNTER.lock().unwrap_or_else(PoisonError::into_inner);
1239 let Some(id) = counter.checked_add(1) else {
1240 // in case the panic handler ends up calling `ThreadId::new()`,
1241 // avoid reentrant lock acquire.
1242 drop(counter);
1243 exhausted();
1244 };
1245
1246 *counter = id;
1247 drop(counter);
1248 ThreadId(NonZero::new(id).unwrap())
1249 }
1250 }
1251 }
1252
1253 #[cfg(any(not(target_thread_local), target_has_atomic = "64"))]
1254 fn from_u64(v: u64) -> Option<ThreadId> {
1255 NonZero::new(v).map(ThreadId)
1256 }
1257
1258 /// This returns a numeric identifier for the thread identified by this
1259 /// `ThreadId`.
1260 ///
1261 /// As noted in the documentation for the type itself, it is essentially an
1262 /// opaque ID, but is guaranteed to be unique for each thread. The returned
1263 /// value is entirely opaque -- only equality testing is stable. Note that
1264 /// it is not guaranteed which values new threads will return, and this may
1265 /// change across Rust versions.
1266 #[must_use]
1267 #[unstable(feature = "thread_id_value", issue = "67939")]
1268 pub fn as_u64(&self) -> NonZero<u64> {
1269 self.0
1270 }
1271}
1272
1273////////////////////////////////////////////////////////////////////////////////
1274// Thread
1275////////////////////////////////////////////////////////////////////////////////
1276
1277// This module ensures private fields are kept private, which is necessary to enforce the safety requirements.
1278mod thread_name_string {
1279 use crate::ffi::{CStr, CString};
1280 use crate::str;
1281
1282 /// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated.
1283 pub(crate) struct ThreadNameString {
1284 inner: CString,
1285 }
1286
1287 impl From<String> for ThreadNameString {
1288 fn from(s: String) -> Self {
1289 Self {
1290 inner: CString::new(s).expect("thread name may not contain interior null bytes"),
1291 }
1292 }
1293 }
1294
1295 impl ThreadNameString {
1296 pub fn as_cstr(&self) -> &CStr {
1297 &self.inner
1298 }
1299
1300 pub fn as_str(&self) -> &str {
1301 // SAFETY: `ThreadNameString` is guaranteed to be UTF-8.
1302 unsafe { str::from_utf8_unchecked(self.inner.to_bytes()) }
1303 }
1304 }
1305}
1306
1307use thread_name_string::ThreadNameString;
1308
1309/// Store the ID of the main thread.
1310///
1311/// The thread handle for the main thread is created lazily, and this might even
1312/// happen pre-main. Since not every platform has a way to identify the main
1313/// thread when that happens – macOS's `pthread_main_np` function being a notable
1314/// exception – we cannot assign it the right name right then. Instead, in our
1315/// runtime startup code, we remember the thread ID of the main thread (through
1316/// this modules `set` function) and use it to identify the main thread from then
1317/// on. This works reliably and has the additional advantage that we can report
1318/// the right thread name on main even after the thread handle has been destroyed.
1319/// Note however that this also means that the name reported in pre-main functions
1320/// will be incorrect, but that's just something we have to live with.
1321pub(crate) mod main_thread {
1322 cfg_select! {
1323 target_has_atomic = "64" => {
1324 use super::ThreadId;
1325 use crate::sync::atomic::{Atomic, AtomicU64};
1326 use crate::sync::atomic::Ordering::Relaxed;
1327
1328 static MAIN: Atomic<u64> = AtomicU64::new(0);
1329
1330 pub(super) fn get() -> Option<ThreadId> {
1331 ThreadId::from_u64(MAIN.load(Relaxed))
1332 }
1333
1334 /// # Safety
1335 /// May only be called once.
1336 pub(crate) unsafe fn set(id: ThreadId) {
1337 MAIN.store(id.as_u64().get(), Relaxed)
1338 }
1339 }
1340 _ => {
1341 use super::ThreadId;
1342 use crate::mem::MaybeUninit;
1343 use crate::sync::atomic::{Atomic, AtomicBool};
1344 use crate::sync::atomic::Ordering::{Acquire, Release};
1345
1346 static INIT: Atomic<bool> = AtomicBool::new(false);
1347 static mut MAIN: MaybeUninit<ThreadId> = MaybeUninit::uninit();
1348
1349 pub(super) fn get() -> Option<ThreadId> {
1350 if INIT.load(Acquire) {
1351 Some(unsafe { MAIN.assume_init() })
1352 } else {
1353 None
1354 }
1355 }
1356
1357 /// # Safety
1358 /// May only be called once.
1359 pub(crate) unsafe fn set(id: ThreadId) {
1360 unsafe { MAIN = MaybeUninit::new(id) };
1361 INIT.store(true, Release);
1362 }
1363 }
1364 }
1365}
1366
1367/// Run a function with the current thread's name.
1368///
1369/// Modulo thread local accesses, this function is safe to call from signal
1370/// handlers and in similar circumstances where allocations are not possible.
1371pub(crate) fn with_current_name<F, R>(f: F) -> R
1372where
1373 F: FnOnce(Option<&str>) -> R,
1374{
1375 try_with_current(|thread| {
1376 if let Some(thread) = thread {
1377 // If there is a current thread handle, try to use the name stored
1378 // there.
1379 if let Some(name) = &thread.inner.name {
1380 return f(Some(name.as_str()));
1381 } else if Some(thread.inner.id) == main_thread::get() {
1382 // The main thread doesn't store its name in the handle, we must
1383 // identify it through its ID. Since we already have the `Thread`,
1384 // we can retrieve the ID from it instead of going through another
1385 // thread local.
1386 return f(Some("main"));
1387 }
1388 } else if let Some(main) = main_thread::get()
1389 && let Some(id) = current::id::get()
1390 && id == main
1391 {
1392 // The main thread doesn't always have a thread handle, we must
1393 // identify it through its ID instead. The checks are ordered so
1394 // that the current ID is only loaded if it is actually needed,
1395 // since loading it from TLS might need multiple expensive accesses.
1396 return f(Some("main"));
1397 }
1398
1399 f(None)
1400 })
1401}
1402
1403/// The internal representation of a `Thread` handle
1404///
1405/// We explicitly set the alignment for our guarantee in Thread::into_raw. This
1406/// allows applications to stuff extra metadata bits into the alignment, which
1407/// can be rather useful when working with atomics.
1408#[repr(align(8))]
1409struct Inner {
1410 name: Option<ThreadNameString>,
1411 id: ThreadId,
1412 parker: Parker,
1413}
1414
1415impl Inner {
1416 fn parker(self: Pin<&Self>) -> Pin<&Parker> {
1417 unsafe { Pin::map_unchecked(self, |inner| &inner.parker) }
1418 }
1419}
1420
1421#[derive(Clone)]
1422#[stable(feature = "rust1", since = "1.0.0")]
1423/// A handle to a thread.
1424///
1425/// Threads are represented via the `Thread` type, which you can get in one of
1426/// two ways:
1427///
1428/// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1429/// function, and calling [`thread`][`JoinHandle::thread`] on the
1430/// [`JoinHandle`].
1431/// * By requesting the current thread, using the [`thread::current`] function.
1432///
1433/// The [`thread::current`] function is available even for threads not spawned
1434/// by the APIs of this module.
1435///
1436/// There is usually no need to create a `Thread` struct yourself, one
1437/// should instead use a function like `spawn` to create new threads, see the
1438/// docs of [`Builder`] and [`spawn`] for more details.
1439///
1440/// [`thread::current`]: current::current
1441pub struct Thread {
1442 inner: Pin<Arc<Inner>>,
1443}
1444
1445impl Thread {
1446 pub(crate) fn new(id: ThreadId, name: Option<String>) -> Thread {
1447 let name = name.map(ThreadNameString::from);
1448
1449 // We have to use `unsafe` here to construct the `Parker` in-place,
1450 // which is required for the UNIX implementation.
1451 //
1452 // SAFETY: We pin the Arc immediately after creation, so its address never
1453 // changes.
1454 let inner = unsafe {
1455 let mut arc = Arc::<Inner>::new_uninit();
1456 let ptr = Arc::get_mut_unchecked(&mut arc).as_mut_ptr();
1457 (&raw mut (*ptr).name).write(name);
1458 (&raw mut (*ptr).id).write(id);
1459 Parker::new_in_place(&raw mut (*ptr).parker);
1460 Pin::new_unchecked(arc.assume_init())
1461 };
1462
1463 Thread { inner }
1464 }
1465
1466 /// Like the public [`park`], but callable on any handle. This is used to
1467 /// allow parking in TLS destructors.
1468 ///
1469 /// # Safety
1470 /// May only be called from the thread to which this handle belongs.
1471 pub(crate) unsafe fn park(&self) {
1472 unsafe { self.inner.as_ref().parker().park() }
1473 }
1474
1475 /// Like the public [`park_timeout`], but callable on any handle. This is
1476 /// used to allow parking in TLS destructors.
1477 ///
1478 /// # Safety
1479 /// May only be called from the thread to which this handle belongs.
1480 pub(crate) unsafe fn park_timeout(&self, dur: Duration) {
1481 unsafe { self.inner.as_ref().parker().park_timeout(dur) }
1482 }
1483
1484 /// Atomically makes the handle's token available if it is not already.
1485 ///
1486 /// Every thread is equipped with some basic low-level blocking support, via
1487 /// the [`park`][park] function and the `unpark()` method. These can be
1488 /// used as a more CPU-efficient implementation of a spinlock.
1489 ///
1490 /// See the [park documentation][park] for more details.
1491 ///
1492 /// # Examples
1493 ///
1494 /// ```
1495 /// use std::thread;
1496 /// use std::time::Duration;
1497 ///
1498 /// let parked_thread = thread::Builder::new()
1499 /// .spawn(|| {
1500 /// println!("Parking thread");
1501 /// thread::park();
1502 /// println!("Thread unparked");
1503 /// })
1504 /// .unwrap();
1505 ///
1506 /// // Let some time pass for the thread to be spawned.
1507 /// thread::sleep(Duration::from_millis(10));
1508 ///
1509 /// println!("Unpark the thread");
1510 /// parked_thread.thread().unpark();
1511 ///
1512 /// parked_thread.join().unwrap();
1513 /// ```
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 #[inline]
1516 pub fn unpark(&self) {
1517 self.inner.as_ref().parker().unpark();
1518 }
1519
1520 /// Gets the thread's unique identifier.
1521 ///
1522 /// # Examples
1523 ///
1524 /// ```
1525 /// use std::thread;
1526 ///
1527 /// let other_thread = thread::spawn(|| {
1528 /// thread::current().id()
1529 /// });
1530 ///
1531 /// let other_thread_id = other_thread.join().unwrap();
1532 /// assert!(thread::current().id() != other_thread_id);
1533 /// ```
1534 #[stable(feature = "thread_id", since = "1.19.0")]
1535 #[must_use]
1536 pub fn id(&self) -> ThreadId {
1537 self.inner.id
1538 }
1539
1540 /// Gets the thread's name.
1541 ///
1542 /// For more information about named threads, see
1543 /// [this module-level documentation][naming-threads].
1544 ///
1545 /// # Examples
1546 ///
1547 /// Threads by default have no name specified:
1548 ///
1549 /// ```
1550 /// use std::thread;
1551 ///
1552 /// let builder = thread::Builder::new();
1553 ///
1554 /// let handler = builder.spawn(|| {
1555 /// assert!(thread::current().name().is_none());
1556 /// }).unwrap();
1557 ///
1558 /// handler.join().unwrap();
1559 /// ```
1560 ///
1561 /// Thread with a specified name:
1562 ///
1563 /// ```
1564 /// use std::thread;
1565 ///
1566 /// let builder = thread::Builder::new()
1567 /// .name("foo".into());
1568 ///
1569 /// let handler = builder.spawn(|| {
1570 /// assert_eq!(thread::current().name(), Some("foo"))
1571 /// }).unwrap();
1572 ///
1573 /// handler.join().unwrap();
1574 /// ```
1575 ///
1576 /// [naming-threads]: ./index.html#naming-threads
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 #[must_use]
1579 pub fn name(&self) -> Option<&str> {
1580 if let Some(name) = &self.inner.name {
1581 Some(name.as_str())
1582 } else if main_thread::get() == Some(self.inner.id) {
1583 Some("main")
1584 } else {
1585 None
1586 }
1587 }
1588
1589 /// Consumes the `Thread`, returning a raw pointer.
1590 ///
1591 /// To avoid a memory leak the pointer must be converted
1592 /// back into a `Thread` using [`Thread::from_raw`]. The pointer is
1593 /// guaranteed to be aligned to at least 8 bytes.
1594 ///
1595 /// # Examples
1596 ///
1597 /// ```
1598 /// #![feature(thread_raw)]
1599 ///
1600 /// use std::thread::{self, Thread};
1601 ///
1602 /// let thread = thread::current();
1603 /// let id = thread.id();
1604 /// let ptr = Thread::into_raw(thread);
1605 /// unsafe {
1606 /// assert_eq!(Thread::from_raw(ptr).id(), id);
1607 /// }
1608 /// ```
1609 #[unstable(feature = "thread_raw", issue = "97523")]
1610 pub fn into_raw(self) -> *const () {
1611 // Safety: We only expose an opaque pointer, which maintains the `Pin` invariant.
1612 let inner = unsafe { Pin::into_inner_unchecked(self.inner) };
1613 Arc::into_raw(inner) as *const ()
1614 }
1615
1616 /// Constructs a `Thread` from a raw pointer.
1617 ///
1618 /// The raw pointer must have been previously returned
1619 /// by a call to [`Thread::into_raw`].
1620 ///
1621 /// # Safety
1622 ///
1623 /// This function is unsafe because improper use may lead
1624 /// to memory unsafety, even if the returned `Thread` is never
1625 /// accessed.
1626 ///
1627 /// Creating a `Thread` from a pointer other than one returned
1628 /// from [`Thread::into_raw`] is **undefined behavior**.
1629 ///
1630 /// Calling this function twice on the same raw pointer can lead
1631 /// to a double-free if both `Thread` instances are dropped.
1632 #[unstable(feature = "thread_raw", issue = "97523")]
1633 pub unsafe fn from_raw(ptr: *const ()) -> Thread {
1634 // Safety: Upheld by caller.
1635 unsafe { Thread { inner: Pin::new_unchecked(Arc::from_raw(ptr as *const Inner)) } }
1636 }
1637
1638 fn cname(&self) -> Option<&CStr> {
1639 if let Some(name) = &self.inner.name {
1640 Some(name.as_cstr())
1641 } else if main_thread::get() == Some(self.inner.id) {
1642 Some(c"main")
1643 } else {
1644 None
1645 }
1646 }
1647}
1648
1649#[stable(feature = "rust1", since = "1.0.0")]
1650impl fmt::Debug for Thread {
1651 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1652 f.debug_struct("Thread")
1653 .field("id", &self.id())
1654 .field("name", &self.name())
1655 .finish_non_exhaustive()
1656 }
1657}
1658
1659////////////////////////////////////////////////////////////////////////////////
1660// JoinHandle
1661////////////////////////////////////////////////////////////////////////////////
1662
1663/// A specialized [`Result`] type for threads.
1664///
1665/// Indicates the manner in which a thread exited.
1666///
1667/// The value contained in the `Result::Err` variant
1668/// is the value the thread panicked with;
1669/// that is, the argument the `panic!` macro was called with.
1670/// Unlike with normal errors, this value doesn't implement
1671/// the [`Error`](crate::error::Error) trait.
1672///
1673/// Thus, a sensible way to handle a thread panic is to either:
1674///
1675/// 1. propagate the panic with [`std::panic::resume_unwind`]
1676/// 2. or in case the thread is intended to be a subsystem boundary
1677/// that is supposed to isolate system-level failures,
1678/// match on the `Err` variant and handle the panic in an appropriate way
1679///
1680/// A thread that completes without panicking is considered to exit successfully.
1681///
1682/// # Examples
1683///
1684/// Matching on the result of a joined thread:
1685///
1686/// ```no_run
1687/// use std::{fs, thread, panic};
1688///
1689/// fn copy_in_thread() -> thread::Result<()> {
1690/// thread::spawn(|| {
1691/// fs::copy("foo.txt", "bar.txt").unwrap();
1692/// }).join()
1693/// }
1694///
1695/// fn main() {
1696/// match copy_in_thread() {
1697/// Ok(_) => println!("copy succeeded"),
1698/// Err(e) => panic::resume_unwind(e),
1699/// }
1700/// }
1701/// ```
1702///
1703/// [`Result`]: crate::result::Result
1704/// [`std::panic::resume_unwind`]: crate::panic::resume_unwind
1705#[stable(feature = "rust1", since = "1.0.0")]
1706#[doc(search_unbox)]
1707pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
1708
1709// This packet is used to communicate the return value between the spawned
1710// thread and the rest of the program. It is shared through an `Arc` and
1711// there's no need for a mutex here because synchronization happens with `join()`
1712// (the caller will never read this packet until the thread has exited).
1713//
1714// An Arc to the packet is stored into a `JoinInner` which in turns is placed
1715// in `JoinHandle`.
1716struct Packet<'scope, T> {
1717 scope: Option<Arc<scoped::ScopeData>>,
1718 result: UnsafeCell<Option<Result<T>>>,
1719 _marker: PhantomData<Option<&'scope scoped::ScopeData>>,
1720}
1721
1722// Due to the usage of `UnsafeCell` we need to manually implement Sync.
1723// The type `T` should already always be Send (otherwise the thread could not
1724// have been created) and the Packet is Sync because all access to the
1725// `UnsafeCell` synchronized (by the `join()` boundary), and `ScopeData` is Sync.
1726unsafe impl<'scope, T: Send> Sync for Packet<'scope, T> {}
1727
1728impl<'scope, T> Drop for Packet<'scope, T> {
1729 fn drop(&mut self) {
1730 // If this packet was for a thread that ran in a scope, the thread
1731 // panicked, and nobody consumed the panic payload, we make sure
1732 // the scope function will panic.
1733 let unhandled_panic = matches!(self.result.get_mut(), Some(Err(_)));
1734 // Drop the result without causing unwinding.
1735 // This is only relevant for threads that aren't join()ed, as
1736 // join() will take the `result` and set it to None, such that
1737 // there is nothing left to drop here.
1738 // If this panics, we should handle that, because we're outside the
1739 // outermost `catch_unwind` of our thread.
1740 // We just abort in that case, since there's nothing else we can do.
1741 // (And even if we tried to handle it somehow, we'd also need to handle
1742 // the case where the panic payload we get out of it also panics on
1743 // drop, and so on. See issue #86027.)
1744 if let Err(_) = panic::catch_unwind(panic::AssertUnwindSafe(|| {
1745 *self.result.get_mut() = None;
1746 })) {
1747 rtabort!("thread result panicked on drop");
1748 }
1749 // Book-keeping so the scope knows when it's done.
1750 if let Some(scope) = &self.scope {
1751 // Now that there will be no more user code running on this thread
1752 // that can use 'scope, mark the thread as 'finished'.
1753 // It's important we only do this after the `result` has been dropped,
1754 // since dropping it might still use things it borrowed from 'scope.
1755 scope.decrement_num_running_threads(unhandled_panic);
1756 }
1757 }
1758}
1759
1760/// Inner representation for JoinHandle
1761struct JoinInner<'scope, T> {
1762 native: imp::Thread,
1763 thread: Thread,
1764 packet: Arc<Packet<'scope, T>>,
1765}
1766
1767impl<'scope, T> JoinInner<'scope, T> {
1768 fn join(mut self) -> Result<T> {
1769 self.native.join();
1770 Arc::get_mut(&mut self.packet)
1771 // FIXME(fuzzypixelz): returning an error instead of panicking here
1772 // would require updating the documentation of
1773 // `std::thread::Result`; currently we can return `Err` if and only
1774 // if the thread had panicked.
1775 .expect("threads should not terminate unexpectedly")
1776 .result
1777 .get_mut()
1778 .take()
1779 .unwrap()
1780 }
1781}
1782
1783/// An owned permission to join on a thread (block on its termination).
1784///
1785/// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1786/// means that there is no longer any handle to the thread and no way to `join`
1787/// on it.
1788///
1789/// Due to platform restrictions, it is not possible to [`Clone`] this
1790/// handle: the ability to join a thread is a uniquely-owned permission.
1791///
1792/// This `struct` is created by the [`thread::spawn`] function and the
1793/// [`thread::Builder::spawn`] method.
1794///
1795/// # Examples
1796///
1797/// Creation from [`thread::spawn`]:
1798///
1799/// ```
1800/// use std::thread;
1801///
1802/// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1803/// // some work here
1804/// });
1805/// ```
1806///
1807/// Creation from [`thread::Builder::spawn`]:
1808///
1809/// ```
1810/// use std::thread;
1811///
1812/// let builder = thread::Builder::new();
1813///
1814/// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1815/// // some work here
1816/// }).unwrap();
1817/// ```
1818///
1819/// A thread being detached and outliving the thread that spawned it:
1820///
1821/// ```no_run
1822/// use std::thread;
1823/// use std::time::Duration;
1824///
1825/// let original_thread = thread::spawn(|| {
1826/// let _detached_thread = thread::spawn(|| {
1827/// // Here we sleep to make sure that the first thread returns before.
1828/// thread::sleep(Duration::from_millis(10));
1829/// // This will be called, even though the JoinHandle is dropped.
1830/// println!("♫ Still alive ♫");
1831/// });
1832/// });
1833///
1834/// original_thread.join().expect("The thread being joined has panicked");
1835/// println!("Original thread is joined.");
1836///
1837/// // We make sure that the new thread has time to run, before the main
1838/// // thread returns.
1839///
1840/// thread::sleep(Duration::from_millis(1000));
1841/// ```
1842///
1843/// [`thread::Builder::spawn`]: Builder::spawn
1844/// [`thread::spawn`]: spawn
1845#[stable(feature = "rust1", since = "1.0.0")]
1846#[cfg_attr(target_os = "teeos", must_use)]
1847pub struct JoinHandle<T>(JoinInner<'static, T>);
1848
1849#[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1850unsafe impl<T> Send for JoinHandle<T> {}
1851#[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1852unsafe impl<T> Sync for JoinHandle<T> {}
1853
1854impl<T> JoinHandle<T> {
1855 /// Extracts a handle to the underlying thread.
1856 ///
1857 /// # Examples
1858 ///
1859 /// ```
1860 /// use std::thread;
1861 ///
1862 /// let builder = thread::Builder::new();
1863 ///
1864 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1865 /// // some work here
1866 /// }).unwrap();
1867 ///
1868 /// let thread = join_handle.thread();
1869 /// println!("thread id: {:?}", thread.id());
1870 /// ```
1871 #[stable(feature = "rust1", since = "1.0.0")]
1872 #[must_use]
1873 pub fn thread(&self) -> &Thread {
1874 &self.0.thread
1875 }
1876
1877 /// Waits for the associated thread to finish.
1878 ///
1879 /// This function will return immediately if the associated thread has already finished.
1880 ///
1881 /// In terms of [atomic memory orderings], the completion of the associated
1882 /// thread synchronizes with this function returning. In other words, all
1883 /// operations performed by that thread [happen
1884 /// before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) all
1885 /// operations that happen after `join` returns.
1886 ///
1887 /// If the associated thread panics, [`Err`] is returned with the parameter given
1888 /// to [`panic!`] (though see the Notes below).
1889 ///
1890 /// [`Err`]: crate::result::Result::Err
1891 /// [atomic memory orderings]: crate::sync::atomic
1892 ///
1893 /// # Panics
1894 ///
1895 /// This function may panic on some platforms if a thread attempts to join
1896 /// itself or otherwise may create a deadlock with joining threads.
1897 ///
1898 /// # Examples
1899 ///
1900 /// ```
1901 /// use std::thread;
1902 ///
1903 /// let builder = thread::Builder::new();
1904 ///
1905 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1906 /// // some work here
1907 /// }).unwrap();
1908 /// join_handle.join().expect("Couldn't join on the associated thread");
1909 /// ```
1910 ///
1911 /// # Notes
1912 ///
1913 /// If a "foreign" unwinding operation (e.g. an exception thrown from C++
1914 /// code, or a `panic!` in Rust code compiled or linked with a different
1915 /// runtime) unwinds all the way to the thread root, the process may be
1916 /// aborted; see the Notes on [`thread::spawn`]. If the process is not
1917 /// aborted, this function will return a `Result::Err` containing an opaque
1918 /// type.
1919 ///
1920 /// [`catch_unwind`]: ../../std/panic/fn.catch_unwind.html
1921 /// [`thread::spawn`]: spawn
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 pub fn join(self) -> Result<T> {
1924 self.0.join()
1925 }
1926
1927 /// Checks if the associated thread has finished running its main function.
1928 ///
1929 /// `is_finished` supports implementing a non-blocking join operation, by checking
1930 /// `is_finished`, and calling `join` if it returns `true`. This function does not block. To
1931 /// block while waiting on the thread to finish, use [`join`][Self::join].
1932 ///
1933 /// This might return `true` for a brief moment after the thread's main
1934 /// function has returned, but before the thread itself has stopped running.
1935 /// However, once this returns `true`, [`join`][Self::join] can be expected
1936 /// to return quickly, without blocking for any significant amount of time.
1937 #[stable(feature = "thread_is_running", since = "1.61.0")]
1938 pub fn is_finished(&self) -> bool {
1939 Arc::strong_count(&self.0.packet) == 1
1940 }
1941}
1942
1943impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1944 fn as_inner(&self) -> &imp::Thread {
1945 &self.0.native
1946 }
1947}
1948
1949impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1950 fn into_inner(self) -> imp::Thread {
1951 self.0.native
1952 }
1953}
1954
1955#[stable(feature = "std_debug", since = "1.16.0")]
1956impl<T> fmt::Debug for JoinHandle<T> {
1957 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1958 f.debug_struct("JoinHandle").finish_non_exhaustive()
1959 }
1960}
1961
1962fn _assert_sync_and_send() {
1963 fn _assert_both<T: Send + Sync>() {}
1964 _assert_both::<JoinHandle<()>>();
1965 _assert_both::<Thread>();
1966}
1967
1968/// Returns an estimate of the default amount of parallelism a program should use.
1969///
1970/// Parallelism is a resource. A given machine provides a certain capacity for
1971/// parallelism, i.e., a bound on the number of computations it can perform
1972/// simultaneously. This number often corresponds to the amount of CPUs a
1973/// computer has, but it may diverge in various cases.
1974///
1975/// Host environments such as VMs or container orchestrators may want to
1976/// restrict the amount of parallelism made available to programs in them. This
1977/// is often done to limit the potential impact of (unintentionally)
1978/// resource-intensive programs on other programs running on the same machine.
1979///
1980/// # Limitations
1981///
1982/// The purpose of this API is to provide an easy and portable way to query
1983/// the default amount of parallelism the program should use. Among other things it
1984/// does not expose information on NUMA regions, does not account for
1985/// differences in (co)processor capabilities or current system load,
1986/// and will not modify the program's global state in order to more accurately
1987/// query the amount of available parallelism.
1988///
1989/// Where both fixed steady-state and burst limits are available the steady-state
1990/// capacity will be used to ensure more predictable latencies.
1991///
1992/// Resource limits can be changed during the runtime of a program, therefore the value is
1993/// not cached and instead recomputed every time this function is called. It should not be
1994/// called from hot code.
1995///
1996/// The value returned by this function should be considered a simplified
1997/// approximation of the actual amount of parallelism available at any given
1998/// time. To get a more detailed or precise overview of the amount of
1999/// parallelism available to the program, you may wish to use
2000/// platform-specific APIs as well. The following platform limitations currently
2001/// apply to `available_parallelism`:
2002///
2003/// On Windows:
2004/// - It may undercount the amount of parallelism available on systems with more
2005/// than 64 logical CPUs. However, programs typically need specific support to
2006/// take advantage of more than 64 logical CPUs, and in the absence of such
2007/// support, the number returned by this function accurately reflects the
2008/// number of logical CPUs the program can use by default.
2009/// - It may overcount the amount of parallelism available on systems limited by
2010/// process-wide affinity masks, or job object limitations.
2011///
2012/// On Linux:
2013/// - It may overcount the amount of parallelism available when limited by a
2014/// process-wide affinity mask or cgroup quotas and `sched_getaffinity()` or cgroup fs can't be
2015/// queried, e.g. due to sandboxing.
2016/// - It may undercount the amount of parallelism if the current thread's affinity mask
2017/// does not reflect the process' cpuset, e.g. due to pinned threads.
2018/// - If the process is in a cgroup v1 cpu controller, this may need to
2019/// scan mountpoints to find the corresponding cgroup v1 controller,
2020/// which may take time on systems with large numbers of mountpoints.
2021/// (This does not apply to cgroup v2, or to processes not in a
2022/// cgroup.)
2023/// - It does not attempt to take `ulimit` into account. If there is a limit set on the number of
2024/// threads, `available_parallelism` cannot know how much of that limit a Rust program should
2025/// take, or know in a reliable and race-free way how much of that limit is already taken.
2026///
2027/// On all targets:
2028/// - It may overcount the amount of parallelism available when running in a VM
2029/// with CPU usage limits (e.g. an overcommitted host).
2030///
2031/// # Errors
2032///
2033/// This function will, but is not limited to, return errors in the following
2034/// cases:
2035///
2036/// - If the amount of parallelism is not known for the target platform.
2037/// - If the program lacks permission to query the amount of parallelism made
2038/// available to it.
2039///
2040/// # Examples
2041///
2042/// ```
2043/// # #![allow(dead_code)]
2044/// use std::{io, thread};
2045///
2046/// fn main() -> io::Result<()> {
2047/// let count = thread::available_parallelism()?.get();
2048/// assert!(count >= 1_usize);
2049/// Ok(())
2050/// }
2051/// ```
2052#[doc(alias = "available_concurrency")] // Alias for a previous name we gave this API on unstable.
2053#[doc(alias = "hardware_concurrency")] // Alias for C++ `std::thread::hardware_concurrency`.
2054#[doc(alias = "num_cpus")] // Alias for a popular ecosystem crate which provides similar functionality.
2055#[stable(feature = "available_parallelism", since = "1.59.0")]
2056pub fn available_parallelism() -> io::Result<NonZero<usize>> {
2057 imp::available_parallelism()
2058}