2016-03-04 22:37:11 +00:00
|
|
|
//! Native threads.
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
|
|
|
//! ## The threading model
|
|
|
|
//!
|
|
|
|
//! An executing Rust program consists of a collection of native OS threads,
|
2016-05-01 20:59:20 +00:00
|
|
|
//! each with their own stack and local state. Threads can be named, and
|
|
|
|
//! provide some built-in support for low-level synchronization.
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
2014-12-14 08:05:32 +00:00
|
|
|
//! Communication between threads can be done through
|
2016-12-17 17:09:05 +00:00
|
|
|
//! [channels], Rust's message-passing types, along with [other forms of thread
|
2014-12-14 08:05:32 +00:00
|
|
|
//! synchronization](../../std/sync/index.html) and shared-memory data
|
|
|
|
//! structures. In particular, types that are guaranteed to be
|
|
|
|
//! threadsafe are easily shared between threads using the
|
2016-12-17 17:09:05 +00:00
|
|
|
//! atomically-reference-counted container, [`Arc`].
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
|
|
|
//! Fatal logic errors in Rust cause *thread panic*, during which
|
|
|
|
//! a thread will unwind the stack, running destructors and freeing
|
2017-11-02 09:26:46 +00:00
|
|
|
//! owned resources. While not meant as a 'try/catch' mechanism, panics
|
2017-11-02 16:30:02 +00:00
|
|
|
//! in Rust can nonetheless be caught (unless compiling with `panic=abort`) with
|
2017-11-02 16:29:52 +00:00
|
|
|
//! [`catch_unwind`](../../std/panic/fn.catch_unwind.html) and recovered
|
2017-11-02 09:26:46 +00:00
|
|
|
//! from, or alternatively be resumed with
|
2017-11-02 16:29:52 +00:00
|
|
|
//! [`resume_unwind`](../../std/panic/fn.resume_unwind.html). If the panic
|
2017-11-02 09:26:46 +00:00
|
|
|
//! is not caught the thread will exit, but the panic may optionally be
|
2017-11-02 17:09:31 +00:00
|
|
|
//! detected from a different thread with [`join`]. If the main thread panics
|
2017-11-02 09:26:46 +00:00
|
|
|
//! without the panic being caught, the application will exit with a
|
|
|
|
//! non-zero exit code.
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
|
|
|
//! When the main thread of a Rust program terminates, the entire program shuts
|
|
|
|
//! down, even if other threads are still running. However, this module provides
|
|
|
|
//! convenient facilities for automatically waiting for the termination of a
|
2021-08-07 15:33:18 +00:00
|
|
|
//! thread (i.e., join).
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
|
|
|
//! ## Spawning a thread
|
|
|
|
//!
|
2016-12-17 17:09:05 +00:00
|
|
|
//! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
|
|
|
//! ```rust
|
2015-02-17 23:10:25 +00:00
|
|
|
//! use std::thread;
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
2015-02-17 23:10:25 +00:00
|
|
|
//! thread::spawn(move || {
|
2015-02-22 18:43:45 +00:00
|
|
|
//! // some work here
|
2014-12-14 08:05:32 +00:00
|
|
|
//! });
|
2014-11-25 16:52:10 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2021-08-07 15:33:18 +00:00
|
|
|
//! In this example, the spawned thread is "detached," which means that there is
|
|
|
|
//! no way for the program to learn when the spawned thread completes or otherwise
|
|
|
|
//! terminates.
|
Stabilize std::thread
This commit takes a first pass at stabilizing `std::thread`:
* It removes the `detach` method in favor of two constructors -- `spawn`
for detached threads, `scoped` for "scoped" (i.e., must-join)
threads. This addresses some of the surprise/frustrating debug
sessions with the previous API, in which `spawn` produced a guard that
on destruction joined the thread (unless `detach` was called).
The reason to have the division in part is that `Send` will soon not
imply `'static`, which means that `scoped` thread creation can take a
closure over *shared stack data* of the parent thread. On the other
hand, this means that the parent must not pop the relevant stack
frames while the child thread is running. The `JoinGuard` is used to
prevent this from happening by joining on drop (if you have not
already explicitly `join`ed.) The APIs around `scoped` are
future-proofed for the `Send` changes by taking an additional lifetime
parameter. With the current definition of `Send`, this is forced to be
`'static`, but when `Send` changes these APIs will gain their full
flexibility immediately.
Threads that are `spawn`ed, on the other hand, are detached from the
start and do not yield an RAII guard.
The hope is that, by making `scoped` an explicit opt-in with a very
suggestive name, it will be drastically less likely to be caught by a
surprising deadlock due to an implicit join at the end of a scope.
* The module itself is marked stable.
* Existing methods other than `spawn` and `scoped` are marked stable.
The migration path is:
```rust
Thread::spawn(f).detached()
```
becomes
```rust
Thread::spawn(f)
```
while
```rust
let res = Thread::spawn(f);
res.join()
```
becomes
```rust
let res = Thread::scoped(f);
res.join()
```
[breaking-change]
2015-01-05 23:45:18 +00:00
|
|
|
//!
|
2021-08-07 15:33:18 +00:00
|
|
|
//! To learn when a thread completes, it is necessary to capture the [`JoinHandle`]
|
|
|
|
//! object that is returned by the call to [`spawn`], which provides
|
|
|
|
//! a `join` method that allows the caller to wait for the completion of the
|
|
|
|
//! spawned thread:
|
2015-04-13 21:48:17 +00:00
|
|
|
//!
|
|
|
|
//! ```rust
|
|
|
|
//! use std::thread;
|
|
|
|
//!
|
2021-08-07 15:33:18 +00:00
|
|
|
//! let thread_join_handle = thread::spawn(move || {
|
2015-04-13 21:48:17 +00:00
|
|
|
//! // some work here
|
|
|
|
//! });
|
|
|
|
//! // some work here
|
2021-08-07 15:33:18 +00:00
|
|
|
//! let res = thread_join_handle.join();
|
2015-04-13 21:48:17 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2017-05-04 09:11:14 +00:00
|
|
|
//! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
|
2021-08-07 15:33:18 +00:00
|
|
|
//! value produced by the spawned thread, or [`Err`] of the value given to
|
|
|
|
//! a call to [`panic!`] if the thread panicked.
|
|
|
|
//!
|
|
|
|
//! Note that there is no parent/child relationship between a thread that spawns a
|
|
|
|
//! new thread and the thread being spawned. In particular, the spawned thread may or
|
|
|
|
//! may not outlive the spawning thread, unless the spawning thread is the main thread.
|
2015-04-13 21:48:17 +00:00
|
|
|
//!
|
2014-12-14 08:05:32 +00:00
|
|
|
//! ## Configuring threads
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
2016-12-17 17:09:05 +00:00
|
|
|
//! A new thread can be configured before it is spawned via the [`Builder`] type,
|
2021-08-07 15:33:18 +00:00
|
|
|
//! which currently allows you to set the name and stack size for the thread:
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
|
|
|
//! ```rust
|
2015-04-07 01:52:18 +00:00
|
|
|
//! # #![allow(unused_must_use)]
|
2014-11-25 16:52:10 +00:00
|
|
|
//! use std::thread;
|
|
|
|
//!
|
2021-08-07 15:33:18 +00:00
|
|
|
//! thread::Builder::new().name("thread1".to_string()).spawn(move || {
|
2015-02-22 18:43:45 +00:00
|
|
|
//! println!("Hello, world!");
|
Stabilize std::thread
This commit takes a first pass at stabilizing `std::thread`:
* It removes the `detach` method in favor of two constructors -- `spawn`
for detached threads, `scoped` for "scoped" (i.e., must-join)
threads. This addresses some of the surprise/frustrating debug
sessions with the previous API, in which `spawn` produced a guard that
on destruction joined the thread (unless `detach` was called).
The reason to have the division in part is that `Send` will soon not
imply `'static`, which means that `scoped` thread creation can take a
closure over *shared stack data* of the parent thread. On the other
hand, this means that the parent must not pop the relevant stack
frames while the child thread is running. The `JoinGuard` is used to
prevent this from happening by joining on drop (if you have not
already explicitly `join`ed.) The APIs around `scoped` are
future-proofed for the `Send` changes by taking an additional lifetime
parameter. With the current definition of `Send`, this is forced to be
`'static`, but when `Send` changes these APIs will gain their full
flexibility immediately.
Threads that are `spawn`ed, on the other hand, are detached from the
start and do not yield an RAII guard.
The hope is that, by making `scoped` an explicit opt-in with a very
suggestive name, it will be drastically less likely to be caught by a
surprising deadlock due to an implicit join at the end of a scope.
* The module itself is marked stable.
* Existing methods other than `spawn` and `scoped` are marked stable.
The migration path is:
```rust
Thread::spawn(f).detached()
```
becomes
```rust
Thread::spawn(f)
```
while
```rust
let res = Thread::spawn(f);
res.join()
```
becomes
```rust
let res = Thread::scoped(f);
res.join()
```
[breaking-change]
2015-01-05 23:45:18 +00:00
|
|
|
//! });
|
2014-11-25 16:52:10 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2016-05-01 20:59:20 +00:00
|
|
|
//! ## The `Thread` type
|
|
|
|
//!
|
2016-12-17 17:09:05 +00:00
|
|
|
//! Threads are represented via the [`Thread`] type, which you can get in one of
|
2016-05-01 20:59:20 +00:00
|
|
|
//! two ways:
|
|
|
|
//!
|
2018-11-27 02:59:49 +00:00
|
|
|
//! * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
|
2017-04-06 11:57:40 +00:00
|
|
|
//! function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
|
2017-03-12 18:04:52 +00:00
|
|
|
//! * By requesting the current thread, using the [`thread::current`] function.
|
2016-05-01 20:59:20 +00:00
|
|
|
//!
|
2017-03-12 18:04:52 +00:00
|
|
|
//! The [`thread::current`] function is available even for threads not spawned
|
2016-05-01 20:59:20 +00:00
|
|
|
//! by the APIs of this module.
|
|
|
|
//!
|
2015-03-20 07:46:13 +00:00
|
|
|
//! ## Thread-local storage
|
|
|
|
//!
|
2016-09-04 14:16:25 +00:00
|
|
|
//! This module also provides an implementation of thread-local storage for Rust
|
|
|
|
//! programs. Thread-local storage is a method of storing data into a global
|
|
|
|
//! variable that each thread in the program will have its own copy of.
|
2015-03-20 07:46:13 +00:00
|
|
|
//! Threads do not share this data, so accesses do not need to be synchronized.
|
|
|
|
//!
|
2016-09-04 14:16:25 +00:00
|
|
|
//! A thread-local key owns the value it contains and will destroy the value when the
|
|
|
|
//! thread exits. It is created with the [`thread_local!`] macro and can contain any
|
|
|
|
//! value that is `'static` (no borrowed pointers). It provides an accessor function,
|
|
|
|
//! [`with`], that yields a shared reference to the value to the specified
|
|
|
|
//! closure. Thread-local keys allow only shared access to values, as there would be no
|
|
|
|
//! way to guarantee uniqueness if mutable borrows were allowed. Most values
|
2015-03-20 07:46:13 +00:00
|
|
|
//! will want to make use of some form of **interior mutability** through the
|
2016-09-04 14:16:25 +00:00
|
|
|
//! [`Cell`] or [`RefCell`] types.
|
|
|
|
//!
|
2017-08-13 16:16:42 +00:00
|
|
|
//! ## Naming threads
|
|
|
|
//!
|
2017-08-13 20:23:13 +00:00
|
|
|
//! Threads are able to have associated names for identification purposes. By default, spawned
|
|
|
|
//! threads are unnamed. To specify a name for a thread, build the thread with [`Builder`] and pass
|
|
|
|
//! the desired thread name to [`Builder::name`]. To retrieve the thread name from within the
|
|
|
|
//! thread, use [`Thread::name`]. A couple examples of where the name of a thread gets used:
|
|
|
|
//!
|
|
|
|
//! * If a panic occurs in a named thread, the thread name will be printed in the panic message.
|
2018-11-27 02:59:49 +00:00
|
|
|
//! * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in
|
2017-08-13 20:23:13 +00:00
|
|
|
//! unix-like platforms).
|
2017-08-13 16:16:42 +00:00
|
|
|
//!
|
|
|
|
//! ## Stack size
|
|
|
|
//!
|
|
|
|
//! The default stack size for spawned threads is 2 MiB, though this particular stack size is
|
|
|
|
//! subject to change in the future. There are two ways to manually specify the stack size for
|
|
|
|
//! spawned threads:
|
|
|
|
//!
|
|
|
|
//! * Build the thread with [`Builder`] and pass the desired stack size to [`Builder::stack_size`].
|
|
|
|
//! * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack
|
2017-08-14 19:03:31 +00:00
|
|
|
//! size (in bytes). Note that setting [`Builder::stack_size`] will override this.
|
2017-08-13 16:16:42 +00:00
|
|
|
//!
|
|
|
|
//! Note that the stack size of the main thread is *not* determined by Rust.
|
|
|
|
//!
|
2020-08-20 20:03:00 +00:00
|
|
|
//! [channels]: crate::sync::mpsc
|
|
|
|
//! [`join`]: JoinHandle::join
|
|
|
|
//! [`Result`]: crate::result::Result
|
|
|
|
//! [`Ok`]: crate::result::Result::Ok
|
|
|
|
//! [`Err`]: crate::result::Result::Err
|
|
|
|
//! [`thread::current`]: current
|
|
|
|
//! [`thread::Result`]: Result
|
|
|
|
//! [`unpark`]: Thread::unpark
|
|
|
|
//! [`thread::park_timeout`]: park_timeout
|
|
|
|
//! [`Cell`]: crate::cell::Cell
|
|
|
|
//! [`RefCell`]: crate::cell::RefCell
|
|
|
|
//! [`with`]: LocalKey::with
|
2022-04-30 21:02:34 +00:00
|
|
|
//! [`thread_local!`]: crate::thread_local
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#![stable(feature = "rust1", since = "1.0.0")]
|
2020-07-10 21:53:25 +00:00
|
|
|
#![deny(unsafe_op_in_unsafe_fn)]
|
Stabilize std::thread
This commit takes a first pass at stabilizing `std::thread`:
* It removes the `detach` method in favor of two constructors -- `spawn`
for detached threads, `scoped` for "scoped" (i.e., must-join)
threads. This addresses some of the surprise/frustrating debug
sessions with the previous API, in which `spawn` produced a guard that
on destruction joined the thread (unless `detach` was called).
The reason to have the division in part is that `Send` will soon not
imply `'static`, which means that `scoped` thread creation can take a
closure over *shared stack data* of the parent thread. On the other
hand, this means that the parent must not pop the relevant stack
frames while the child thread is running. The `JoinGuard` is used to
prevent this from happening by joining on drop (if you have not
already explicitly `join`ed.) The APIs around `scoped` are
future-proofed for the `Send` changes by taking an additional lifetime
parameter. With the current definition of `Send`, this is forced to be
`'static`, but when `Send` changes these APIs will gain their full
flexibility immediately.
Threads that are `spawn`ed, on the other hand, are detached from the
start and do not yield an RAII guard.
The hope is that, by making `scoped` an explicit opt-in with a very
suggestive name, it will be drastically less likely to be caught by a
surprising deadlock due to an implicit join at the end of a scope.
* The module itself is marked stable.
* Existing methods other than `spawn` and `scoped` are marked stable.
The migration path is:
```rust
Thread::spawn(f).detached()
```
becomes
```rust
Thread::spawn(f)
```
while
```rust
let res = Thread::spawn(f);
res.join()
```
becomes
```rust
let res = Thread::scoped(f);
res.join()
```
[breaking-change]
2015-01-05 23:45:18 +00:00
|
|
|
|
2020-08-27 13:45:01 +00:00
|
|
|
#[cfg(all(test, not(target_os = "emscripten")))]
|
|
|
|
mod tests;
|
|
|
|
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::any::Any;
|
|
|
|
use crate::cell::UnsafeCell;
|
|
|
|
use crate::ffi::{CStr, CString};
|
|
|
|
use crate::fmt;
|
|
|
|
use crate::io;
|
2022-06-25 20:30:57 +00:00
|
|
|
use crate::marker::PhantomData;
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::mem;
|
2019-03-19 12:59:38 +00:00
|
|
|
use crate::num::NonZeroU64;
|
2021-04-29 09:40:14 +00:00
|
|
|
use crate::num::NonZeroUsize;
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::panic;
|
|
|
|
use crate::panicking;
|
2022-04-25 13:19:50 +00:00
|
|
|
use crate::pin::Pin;
|
|
|
|
use crate::ptr::addr_of_mut;
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::str;
|
2020-09-19 10:42:14 +00:00
|
|
|
use crate::sync::Arc;
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::sys::thread as imp;
|
|
|
|
use crate::sys_common::thread;
|
|
|
|
use crate::sys_common::thread_info;
|
2020-09-27 10:27:27 +00:00
|
|
|
use crate::sys_common::thread_parker::Parker;
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::sys_common::{AsInner, IntoInner};
|
|
|
|
use crate::time::Duration;
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2015-03-20 07:46:13 +00:00
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Thread-local storage
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2015-04-08 00:10:09 +00:00
|
|
|
#[macro_use]
|
|
|
|
mod local;
|
|
|
|
|
2022-06-09 08:53:45 +00:00
|
|
|
#[stable(feature = "scoped_threads", since = "1.63.0")]
|
2022-01-04 13:51:39 +00:00
|
|
|
mod scoped;
|
|
|
|
|
2022-06-09 08:53:45 +00:00
|
|
|
#[stable(feature = "scoped_threads", since = "1.63.0")]
|
2022-01-04 13:51:39 +00:00
|
|
|
pub use scoped::{scope, Scope, ScopedJoinHandle};
|
|
|
|
|
2015-04-08 00:10:09 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2018-02-27 16:00:01 +00:00
|
|
|
pub use self::local::{AccessError, LocalKey};
|
2015-04-08 00:10:09 +00:00
|
|
|
|
2022-08-06 17:04:22 +00:00
|
|
|
// Select the type used by the thread_local! macro to access TLS keys. There
|
|
|
|
// are three types: "static", "fast", "OS". The "OS" thread local key
|
|
|
|
// type is accessed via platform-specific API calls and is slow, while the "fast"
|
2016-10-04 18:00:27 +00:00
|
|
|
// key type is accessed via code generated via LLVM, where TLS keys are set up
|
2022-08-06 17:04:22 +00:00
|
|
|
// by the elf linker. "static" is for single-threaded platforms where a global
|
|
|
|
// static is sufficient.
|
2016-10-04 18:00:27 +00:00
|
|
|
|
2019-12-21 11:16:18 +00:00
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "none")]
|
2015-12-11 20:42:29 +00:00
|
|
|
#[cfg(target_thread_local)]
|
2022-08-06 16:22:30 +00:00
|
|
|
#[cfg(not(test))]
|
2016-02-17 07:07:09 +00:00
|
|
|
#[doc(hidden)]
|
|
|
|
pub use self::local::fast::Key as __FastLocalKeyInner;
|
2022-08-06 16:22:30 +00:00
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "none")]
|
|
|
|
#[cfg(target_thread_local)]
|
|
|
|
#[cfg(test)] // when building for tests, use real std's key
|
|
|
|
pub use realstd::thread::__FastLocalKeyInner;
|
2022-08-06 17:04:22 +00:00
|
|
|
|
2022-08-06 16:22:30 +00:00
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "none")]
|
|
|
|
#[cfg(target_thread_local)]
|
|
|
|
#[cfg(test)]
|
|
|
|
pub use self::local::fast::Key as __FastLocalKeyInnerUnused; // we import this anyway to silence 'unused' warnings
|
|
|
|
|
2019-12-21 11:16:18 +00:00
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "none")]
|
2015-12-11 20:42:29 +00:00
|
|
|
#[doc(hidden)]
|
2022-08-06 17:04:22 +00:00
|
|
|
#[cfg(not(target_thread_local))]
|
2015-12-11 20:42:29 +00:00
|
|
|
pub use self::local::os::Key as __OsLocalKeyInner;
|
2019-12-21 11:16:18 +00:00
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "none")]
|
2021-10-28 23:28:21 +00:00
|
|
|
#[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
|
2015-12-11 20:42:29 +00:00
|
|
|
#[doc(hidden)]
|
|
|
|
pub use self::local::statik::Key as __StaticLocalKeyInner;
|
2015-03-20 07:46:13 +00:00
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Builder
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2017-05-14 17:35:36 +00:00
|
|
|
/// Thread factory, which can be used in order to configure the properties of
|
|
|
|
/// a new thread.
|
|
|
|
///
|
|
|
|
/// Methods can be chained on it in order to configure it.
|
|
|
|
///
|
|
|
|
/// The two configurations available are:
|
|
|
|
///
|
2017-08-13 16:16:42 +00:00
|
|
|
/// - [`name`]: specifies an [associated name for the thread][naming-threads]
|
|
|
|
/// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
|
2017-05-14 17:35:36 +00:00
|
|
|
///
|
|
|
|
/// The [`spawn`] method will take ownership of the builder and create an
|
|
|
|
/// [`io::Result`] to the thread handle with the given configuration.
|
|
|
|
///
|
|
|
|
/// The [`thread::spawn`] free function uses a `Builder` with default
|
|
|
|
/// configuration and [`unwrap`]s its return value.
|
|
|
|
///
|
|
|
|
/// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
|
|
|
|
/// to recover from a failure to launch a thread, indeed the free function will
|
2018-11-12 18:05:20 +00:00
|
|
|
/// panic where the `Builder` method will return a [`io::Result`].
|
2016-12-20 10:03:11 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new();
|
|
|
|
///
|
|
|
|
/// let handler = builder.spawn(|| {
|
|
|
|
/// // thread code
|
|
|
|
/// }).unwrap();
|
|
|
|
///
|
|
|
|
/// handler.join().unwrap();
|
|
|
|
/// ```
|
2017-05-14 17:35:36 +00:00
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`stack_size`]: Builder::stack_size
|
|
|
|
/// [`name`]: Builder::name
|
|
|
|
/// [`spawn`]: Builder::spawn
|
|
|
|
/// [`thread::spawn`]: spawn
|
|
|
|
/// [`io::Result`]: crate::io::Result
|
|
|
|
/// [`unwrap`]: crate::result::Result::unwrap
|
2017-08-13 16:16:42 +00:00
|
|
|
/// [naming-threads]: ./index.html#naming-threads
|
|
|
|
/// [stack-size]: ./index.html#stack-size
|
2021-10-12 14:48:27 +00:00
|
|
|
#[must_use = "must eventually spawn the thread"]
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2016-11-25 18:21:49 +00:00
|
|
|
#[derive(Debug)]
|
2014-12-14 08:05:32 +00:00
|
|
|
pub struct Builder {
|
2014-11-25 16:52:10 +00:00
|
|
|
// A name for the thread-to-be, for identification in panic messages
|
|
|
|
name: Option<String>,
|
2017-02-22 14:13:22 +00:00
|
|
|
// The size of the stack for the spawned thread in bytes
|
2015-02-18 23:23:55 +00:00
|
|
|
stack_size: Option<usize>,
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
2014-12-14 08:05:32 +00:00
|
|
|
impl Builder {
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Generates the base configuration for spawning a thread, from which
|
2014-11-25 16:52:10 +00:00
|
|
|
/// configuration methods can be chained.
|
2016-12-20 10:03:11 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new()
|
|
|
|
/// .name("foo".into())
|
2019-04-18 11:58:38 +00:00
|
|
|
/// .stack_size(32 * 1024);
|
2016-12-20 10:03:11 +00:00
|
|
|
///
|
|
|
|
/// let handler = builder.spawn(|| {
|
|
|
|
/// // thread code
|
|
|
|
/// }).unwrap();
|
|
|
|
///
|
|
|
|
/// handler.join().unwrap();
|
|
|
|
/// ```
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-12-14 08:05:32 +00:00
|
|
|
pub fn new() -> Builder {
|
2014-11-25 16:52:10 +00:00
|
|
|
Builder { name: None, stack_size: None }
|
|
|
|
}
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Names the thread-to-be. Currently the name is used for identification
|
2014-11-25 16:52:10 +00:00
|
|
|
/// only in panic messages.
|
2016-06-25 11:22:19 +00:00
|
|
|
///
|
2017-09-17 08:19:11 +00:00
|
|
|
/// The name must not contain null bytes (`\0`).
|
|
|
|
///
|
2017-08-13 16:16:42 +00:00
|
|
|
/// For more information about named threads, see
|
|
|
|
/// [this module-level documentation][naming-threads].
|
|
|
|
///
|
2016-06-25 11:22:19 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
2016-12-20 10:03:11 +00:00
|
|
|
/// ```
|
2016-06-25 11:22:19 +00:00
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new()
|
|
|
|
/// .name("foo".into());
|
|
|
|
///
|
|
|
|
/// let handler = builder.spawn(|| {
|
|
|
|
/// assert_eq!(thread::current().name(), Some("foo"))
|
|
|
|
/// }).unwrap();
|
|
|
|
///
|
|
|
|
/// handler.join().unwrap();
|
|
|
|
/// ```
|
2017-08-13 16:16:42 +00:00
|
|
|
///
|
|
|
|
/// [naming-threads]: ./index.html#naming-threads
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-12-14 08:05:32 +00:00
|
|
|
pub fn name(mut self, name: String) -> Builder {
|
2014-11-25 16:52:10 +00:00
|
|
|
self.name = Some(name);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-02-22 14:13:22 +00:00
|
|
|
/// Sets the size of the stack (in bytes) for the new thread.
|
|
|
|
///
|
|
|
|
/// The actual stack size may be greater than this value if
|
2018-11-27 17:57:55 +00:00
|
|
|
/// the platform specifies a minimal stack size.
|
2016-12-20 10:03:11 +00:00
|
|
|
///
|
2017-08-13 16:16:42 +00:00
|
|
|
/// For more information about the stack size for threads, see
|
|
|
|
/// [this module-level documentation][stack-size].
|
|
|
|
///
|
2016-12-20 10:03:11 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
2017-02-22 14:13:22 +00:00
|
|
|
/// let builder = thread::Builder::new().stack_size(32 * 1024);
|
2016-12-20 10:03:11 +00:00
|
|
|
/// ```
|
2017-08-13 16:16:42 +00:00
|
|
|
///
|
|
|
|
/// [stack-size]: ./index.html#stack-size
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 23:23:55 +00:00
|
|
|
pub fn stack_size(mut self, size: usize) -> Builder {
|
2014-11-25 16:52:10 +00:00
|
|
|
self.stack_size = Some(size);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-05-14 17:35:36 +00:00
|
|
|
/// Spawns a new thread by taking ownership of the `Builder`, and returns an
|
|
|
|
/// [`io::Result`] to its [`JoinHandle`].
|
2014-12-14 08:05:32 +00:00
|
|
|
///
|
2017-05-14 17:35:36 +00:00
|
|
|
/// The spawned thread may outlive the caller (unless the caller thread
|
2015-02-17 09:08:53 +00:00
|
|
|
/// is the main thread; the whole process is terminated when the main
|
2015-04-29 03:06:00 +00:00
|
|
|
/// thread finishes). The join handle can be used to block on
|
2021-08-07 15:33:18 +00:00
|
|
|
/// termination of the spawned thread, including recovering its panics.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
2017-05-09 11:20:04 +00:00
|
|
|
/// For a more complete documentation see [`thread::spawn`][`spawn`].
|
|
|
|
///
|
2015-02-17 09:08:53 +00:00
|
|
|
/// # Errors
|
|
|
|
///
|
2016-12-20 10:03:11 +00:00
|
|
|
/// Unlike the [`spawn`] free function, this method yields an
|
|
|
|
/// [`io::Result`] to capture any failure to create the thread at
|
2015-02-17 09:08:53 +00:00
|
|
|
/// the OS level.
|
2016-12-20 10:03:11 +00:00
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`io::Result`]: crate::io::Result
|
2016-12-20 10:03:11 +00:00
|
|
|
///
|
2017-09-17 08:19:11 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if a thread name was set and it contained null bytes.
|
|
|
|
///
|
2016-12-20 10:03:11 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new();
|
|
|
|
///
|
|
|
|
/// let handler = builder.spawn(|| {
|
|
|
|
/// // thread code
|
|
|
|
/// }).unwrap();
|
|
|
|
///
|
|
|
|
/// handler.join().unwrap();
|
|
|
|
/// ```
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-04-13 21:48:17 +00:00
|
|
|
pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
|
|
|
|
where
|
|
|
|
F: FnOnce() -> T,
|
|
|
|
F: Send + 'static,
|
|
|
|
T: Send + 'static,
|
2018-10-13 12:34:31 +00:00
|
|
|
{
|
|
|
|
unsafe { self.spawn_unchecked(f) }
|
|
|
|
}
|
2018-10-13 16:24:47 +00:00
|
|
|
|
2018-10-15 10:48:24 +00:00
|
|
|
/// Spawns a new thread without any lifetime restrictions by taking ownership
|
|
|
|
/// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
|
|
|
|
///
|
|
|
|
/// The spawned thread may outlive the caller (unless the caller thread
|
|
|
|
/// is the main thread; the whole process is terminated when the main
|
|
|
|
/// thread finishes). The join handle can be used to block on
|
2021-08-07 15:33:18 +00:00
|
|
|
/// termination of the spawned thread, including recovering its panics.
|
2018-10-15 10:48:24 +00:00
|
|
|
///
|
|
|
|
/// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
|
|
|
|
/// except for the relaxed lifetime bounds, which render it unsafe.
|
|
|
|
/// For a more complete documentation see [`thread::spawn`][`spawn`].
|
|
|
|
///
|
|
|
|
/// # Errors
|
|
|
|
///
|
|
|
|
/// Unlike the [`spawn`] free function, this method yields an
|
|
|
|
/// [`io::Result`] to capture any failure to create the thread at
|
|
|
|
/// the OS level.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if a thread name was set and it contained null bytes.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
2021-10-08 19:29:04 +00:00
|
|
|
/// The caller has to ensure that the spawned thread does not outlive any
|
|
|
|
/// references in the supplied thread closure and its return type.
|
|
|
|
/// This can be guaranteed in two ways:
|
2018-10-15 10:48:24 +00:00
|
|
|
///
|
|
|
|
/// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
|
|
|
|
/// data is dropped
|
2018-11-27 02:59:49 +00:00
|
|
|
/// - use only types with `'static` lifetime bounds, i.e., those with no or only
|
2018-10-15 10:48:24 +00:00
|
|
|
/// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
|
|
|
|
/// and [`thread::spawn`][`spawn`] enforce this property statically)
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
2018-10-15 12:14:17 +00:00
|
|
|
/// #![feature(thread_spawn_unchecked)]
|
2018-10-15 10:48:24 +00:00
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new();
|
|
|
|
///
|
|
|
|
/// let x = 1;
|
|
|
|
/// let thread_x = &x;
|
|
|
|
///
|
|
|
|
/// let handler = unsafe {
|
|
|
|
/// builder.spawn_unchecked(move || {
|
|
|
|
/// println!("x = {}", *thread_x);
|
2018-10-15 11:22:39 +00:00
|
|
|
/// }).unwrap()
|
|
|
|
/// };
|
2018-10-15 10:48:24 +00:00
|
|
|
///
|
|
|
|
/// // caller has to ensure `join()` is called, otherwise
|
|
|
|
/// // it is possible to access freed memory if `x` gets
|
|
|
|
/// // dropped before the thread closure is executed!
|
2018-10-15 11:47:27 +00:00
|
|
|
/// handler.join().unwrap();
|
2018-10-15 10:48:24 +00:00
|
|
|
/// ```
|
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`io::Result`]: crate::io::Result
|
2018-10-16 20:42:14 +00:00
|
|
|
#[unstable(feature = "thread_spawn_unchecked", issue = "55132")]
|
2018-11-30 05:09:12 +00:00
|
|
|
pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>>
|
|
|
|
where
|
|
|
|
F: FnOnce() -> T,
|
|
|
|
F: Send + 'a,
|
|
|
|
T: Send + 'a,
|
2022-01-04 13:51:39 +00:00
|
|
|
{
|
|
|
|
Ok(JoinHandle(unsafe { self.spawn_unchecked_(f, None) }?))
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn spawn_unchecked_<'a, 'scope, F, T>(
|
|
|
|
self,
|
|
|
|
f: F,
|
2022-06-25 20:30:57 +00:00
|
|
|
scope_data: Option<Arc<scoped::ScopeData>>,
|
2022-01-04 13:51:39 +00:00
|
|
|
) -> io::Result<JoinInner<'scope, T>>
|
|
|
|
where
|
|
|
|
F: FnOnce() -> T,
|
|
|
|
F: Send + 'a,
|
|
|
|
T: Send + 'a,
|
|
|
|
'scope: 'a,
|
2015-02-17 09:08:53 +00:00
|
|
|
{
|
std: Stabilize the `io` module
The new `std::io` module has had some time to bake now, and this commit
stabilizes its functionality. There are still portions of the module which
remain unstable, and below contains a summart of the actions taken.
This commit also deprecates the entire contents of the `old_io` module in a
blanket fashion. All APIs should now have a reasonable replacement in the
new I/O modules.
Stable APIs:
* `std::io` (the name)
* `std::io::prelude` (the name)
* `Read`
* `Read::read`
* `Read::{read_to_end, read_to_string}` after being modified to return a `usize`
for the number of bytes read.
* `Write`
* `Write::write`
* `Write::{write_all, write_fmt}`
* `BufRead`
* `BufRead::{fill_buf, consume}`
* `BufRead::{read_line, read_until}` after being modified to return a `usize`
for the number of bytes read.
* `BufReader`
* `BufReader::{new, with_capacity}`
* `BufReader::{get_ref, get_mut, into_inner}`
* `{Read,BufRead} for BufReader`
* `BufWriter`
* `BufWriter::{new, with_capacity}`
* `BufWriter::{get_ref, get_mut, into_inner}`
* `Write for BufWriter`
* `IntoInnerError`
* `IntoInnerError::{error, into_inner}`
* `{Error,Display} for IntoInnerError`
* `LineWriter`
* `LineWriter::{new, with_capacity}` - `with_capacity` was added
* `LineWriter::{get_ref, get_mut, into_inner}` - `get_mut` was added)
* `Write for LineWriter`
* `BufStream`
* `BufStream::{new, with_capacities}`
* `BufStream::{get_ref, get_mut, into_inner}`
* `{BufRead,Read,Write} for BufStream`
* `stdin`
* `Stdin`
* `Stdin::lock`
* `Stdin::read_line` - added method
* `StdinLock`
* `Read for Stdin`
* `{Read,BufRead} for StdinLock`
* `stdout`
* `Stdout`
* `Stdout::lock`
* `StdoutLock`
* `Write for Stdout`
* `Write for StdoutLock`
* `stderr`
* `Stderr`
* `Stderr::lock`
* `StderrLock`
* `Write for Stderr`
* `Write for StderrLock`
* `io::Result`
* `io::Error`
* `io::Error::last_os_error`
* `{Display, Error} for Error`
Unstable APIs:
(reasons can be found in the commit itself)
* `Write::flush`
* `Seek`
* `ErrorKind`
* `Error::new`
* `Error::from_os_error`
* `Error::kind`
Deprecated APIs
* `Error::description` - available via the `Error` trait
* `Error::detail` - available via the `Display` implementation
* `thread::Builder::{stdout, stderr}`
Changes in functionality:
* `old_io::stdio::set_stderr` is now a noop as the infrastructure for printing
backtraces has migrated to `std::io`.
* The `ReadExt`, `WriteExt`, and `BufReadExt` extension traits were all removed
by folding functionality into the corresponding trait.
[breaking-change]
2015-03-11 21:16:46 +00:00
|
|
|
let Builder { name, stack_size } = self;
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2017-09-09 09:09:34 +00:00
|
|
|
let stack_size = stack_size.unwrap_or_else(thread::min_stack);
|
2015-02-17 09:08:53 +00:00
|
|
|
|
2021-09-16 12:41:09 +00:00
|
|
|
let my_thread = Thread::new(name.map(|name| {
|
|
|
|
CString::new(name).expect("thread name may not contain interior null bytes")
|
|
|
|
}));
|
2014-11-25 16:52:10 +00:00
|
|
|
let their_thread = my_thread.clone();
|
|
|
|
|
2022-06-25 20:30:57 +00:00
|
|
|
let my_packet: Arc<Packet<'scope, T>> = Arc::new(Packet {
|
|
|
|
scope: scope_data,
|
|
|
|
result: UnsafeCell::new(None),
|
|
|
|
_marker: PhantomData,
|
|
|
|
});
|
2015-04-15 05:13:57 +00:00
|
|
|
let their_packet = my_packet.clone();
|
2015-02-17 09:08:53 +00:00
|
|
|
|
2020-11-03 23:11:14 +00:00
|
|
|
let output_capture = crate::io::set_output_capture(None);
|
|
|
|
crate::io::set_output_capture(output_capture.clone());
|
2020-08-05 01:42:36 +00:00
|
|
|
|
2015-02-01 17:44:15 +00:00
|
|
|
let main = move || {
|
2016-03-25 04:46:45 +00:00
|
|
|
if let Some(name) = their_thread.cname() {
|
2015-04-15 05:13:57 +00:00
|
|
|
imp::Thread::set_name(name);
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
2018-10-13 12:34:31 +00:00
|
|
|
|
2020-11-03 23:11:14 +00:00
|
|
|
crate::io::set_output_capture(output_capture);
|
2020-08-05 01:42:36 +00:00
|
|
|
|
2020-07-10 21:53:25 +00:00
|
|
|
// SAFETY: the stack guard passed is the one for the current thread.
|
|
|
|
// This means the current thread's stack and the new thread's stack
|
|
|
|
// are properly set and protected from each other.
|
|
|
|
thread_info::set(unsafe { imp::guard::current() }, their_thread);
|
2018-10-13 12:34:31 +00:00
|
|
|
let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
|
2019-02-10 19:23:21 +00:00
|
|
|
crate::sys_common::backtrace::__rust_begin_short_backtrace(f)
|
2018-10-13 12:34:31 +00:00
|
|
|
}));
|
2020-07-10 21:53:25 +00:00
|
|
|
// SAFETY: `their_packet` as been built just above and moved by the
|
|
|
|
// closure (it is an Arc<...>) and `my_packet` will be stored in the
|
|
|
|
// same `JoinInner` as this closure meaning the mutation will be
|
|
|
|
// safe (not modify it and affect a value far away).
|
2022-01-04 13:51:39 +00:00
|
|
|
unsafe { *their_packet.result.get() = Some(try_result) };
|
2014-11-25 16:52:10 +00:00
|
|
|
};
|
|
|
|
|
2022-06-25 20:30:57 +00:00
|
|
|
if let Some(scope_data) = &my_packet.scope {
|
2022-01-05 10:24:42 +00:00
|
|
|
scope_data.increment_num_running_threads();
|
2022-01-04 13:51:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(JoinInner {
|
2020-07-10 21:53:25 +00:00
|
|
|
// SAFETY:
|
|
|
|
//
|
2018-11-30 05:09:12 +00:00
|
|
|
// `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
|
|
|
|
// through FFI or otherwise used with low-level threading primitives that have no
|
|
|
|
// notion of or way to enforce lifetimes.
|
|
|
|
//
|
|
|
|
// As mentioned in the `Safety` section of this function's documentation, the caller of
|
|
|
|
// this function needs to guarantee that the passed-in lifetime is sufficiently long
|
|
|
|
// for the lifetime of the thread.
|
|
|
|
//
|
|
|
|
// Similarly, the `sys` implementation must guarantee that no references to the closure
|
|
|
|
// exist after the thread has terminated, which is signaled by `Thread::join`
|
|
|
|
// returning.
|
2020-07-10 21:53:25 +00:00
|
|
|
native: unsafe {
|
2022-01-04 13:06:08 +00:00
|
|
|
imp::Thread::new(
|
2020-07-10 21:53:25 +00:00
|
|
|
stack_size,
|
|
|
|
mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(
|
|
|
|
Box::new(main),
|
|
|
|
),
|
2022-01-04 13:06:08 +00:00
|
|
|
)?
|
2020-07-10 21:53:25 +00:00
|
|
|
},
|
2015-02-17 09:08:53 +00:00
|
|
|
thread: my_thread,
|
2022-01-04 13:51:39 +00:00
|
|
|
packet: my_packet,
|
|
|
|
})
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-20 07:46:13 +00:00
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Free functions
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2016-12-21 17:05:11 +00:00
|
|
|
/// Spawns a new thread, returning a [`JoinHandle`] for it.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
2021-08-07 15:33:18 +00:00
|
|
|
/// The join handle provides a [`join`] method that can be used to join the spawned
|
|
|
|
/// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
|
|
|
|
/// the argument given to [`panic!`].
|
|
|
|
///
|
|
|
|
/// If the join handle is dropped, the spawned thread will implicitly be *detached*.
|
|
|
|
/// In this case, the spawned thread may no longer be joined.
|
|
|
|
/// (It is the responsibility of the program to either eventually join threads it
|
|
|
|
/// creates or detach them; otherwise, a resource leak will result.)
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
2021-08-07 15:33:18 +00:00
|
|
|
/// This call will create a thread using default parameters of [`Builder`], if you
|
2017-05-09 11:27:22 +00:00
|
|
|
/// want to specify the stack size or the name of the thread, use this API
|
|
|
|
/// instead.
|
|
|
|
///
|
2017-05-13 18:34:40 +00:00
|
|
|
/// As you can see in the signature of `spawn` there are two constraints on
|
|
|
|
/// both the closure given to `spawn` and its return value, let's explain them:
|
|
|
|
///
|
|
|
|
/// - The `'static` constraint means that the closure and its return value
|
|
|
|
/// must have a lifetime of the whole program execution. The reason for this
|
2021-08-07 15:33:18 +00:00
|
|
|
/// is that threads can outlive the lifetime they have been created in.
|
|
|
|
///
|
2017-05-13 18:34:40 +00:00
|
|
|
/// Indeed if the thread, and by extension its return value, can outlive their
|
|
|
|
/// caller, we need to make sure that they will be valid afterwards, and since
|
|
|
|
/// we *can't* know when it will return we need to have them valid as long as
|
|
|
|
/// possible, that is until the end of the program, hence the `'static`
|
|
|
|
/// lifetime.
|
|
|
|
/// - The [`Send`] constraint is because the closure will need to be passed
|
|
|
|
/// *by value* from the thread where it is spawned to the new thread. Its
|
|
|
|
/// return value will need to be passed from the new thread to the thread
|
|
|
|
/// where it is `join`ed.
|
2017-07-24 18:17:29 +00:00
|
|
|
/// As a reminder, the [`Send`] marker trait expresses that it is safe to be
|
2017-05-13 18:34:40 +00:00
|
|
|
/// passed from thread to thread. [`Sync`] expresses that it is safe to have a
|
|
|
|
/// reference be passed from thread to thread.
|
|
|
|
///
|
2015-02-17 09:08:53 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
2016-12-21 17:05:11 +00:00
|
|
|
/// Panics if the OS fails to create a thread; use [`Builder::spawn`]
|
2015-02-17 09:08:53 +00:00
|
|
|
/// to recover from such errors.
|
2016-12-21 17:05:11 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
2017-05-09 14:57:03 +00:00
|
|
|
/// Creating a thread.
|
2017-05-09 11:20:04 +00:00
|
|
|
///
|
2016-12-21 17:05:11 +00:00
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let handler = thread::spawn(|| {
|
|
|
|
/// // thread code
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// handler.join().unwrap();
|
|
|
|
/// ```
|
2017-05-09 11:20:04 +00:00
|
|
|
///
|
2017-05-10 08:44:58 +00:00
|
|
|
/// As mentioned in the module documentation, threads are usually made to
|
2017-05-09 14:57:03 +00:00
|
|
|
/// communicate using [`channels`], here is how it usually looks.
|
2017-05-09 11:20:04 +00:00
|
|
|
///
|
|
|
|
/// This example also shows how to use `move`, in order to give ownership
|
|
|
|
/// of values to a thread.
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
/// use std::sync::mpsc::channel;
|
|
|
|
///
|
|
|
|
/// let (tx, rx) = channel();
|
|
|
|
///
|
|
|
|
/// let sender = thread::spawn(move || {
|
2017-10-01 18:55:58 +00:00
|
|
|
/// tx.send("Hello, thread".to_owned())
|
|
|
|
/// .expect("Unable to send on channel");
|
2017-05-09 11:20:04 +00:00
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// let receiver = thread::spawn(move || {
|
2017-10-01 18:55:58 +00:00
|
|
|
/// let value = rx.recv().expect("Unable to receive from channel");
|
2022-02-12 19:16:17 +00:00
|
|
|
/// println!("{value}");
|
2017-05-09 11:20:04 +00:00
|
|
|
/// });
|
|
|
|
///
|
2017-10-01 18:55:58 +00:00
|
|
|
/// sender.join().expect("The sender thread has panicked");
|
|
|
|
/// receiver.join().expect("The receiver thread has panicked");
|
2017-05-09 11:20:04 +00:00
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// A thread can also return a value through its [`JoinHandle`], you can use
|
|
|
|
/// this to make asynchronous computations (futures might be more appropriate
|
|
|
|
/// though).
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let computation = thread::spawn(|| {
|
|
|
|
/// // Some expensive computation.
|
|
|
|
/// 42
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// let result = computation.join().unwrap();
|
2022-02-12 19:16:17 +00:00
|
|
|
/// println!("{result}");
|
2017-05-09 11:20:04 +00:00
|
|
|
/// ```
|
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`channels`]: crate::sync::mpsc
|
|
|
|
/// [`join`]: JoinHandle::join
|
|
|
|
/// [`Err`]: crate::result::Result::Err
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-04-13 21:48:17 +00:00
|
|
|
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
|
|
|
|
where
|
|
|
|
F: FnOnce() -> T,
|
|
|
|
F: Send + 'static,
|
|
|
|
T: Send + 'static,
|
|
|
|
{
|
2019-01-22 13:21:54 +00:00
|
|
|
Builder::new().spawn(f).expect("failed to spawn thread")
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Gets a handle to the thread that invokes it.
|
2016-08-25 20:20:21 +00:00
|
|
|
///
|
2016-12-21 17:05:11 +00:00
|
|
|
/// # Examples
|
2016-08-25 20:20:21 +00:00
|
|
|
///
|
|
|
|
/// Getting a handle to the current thread with `thread::current()`:
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let handler = thread::Builder::new()
|
|
|
|
/// .name("named thread".into())
|
|
|
|
/// .spawn(|| {
|
|
|
|
/// let handle = thread::current();
|
|
|
|
/// assert_eq!(handle.name(), Some("named thread"));
|
|
|
|
/// })
|
|
|
|
/// .unwrap();
|
|
|
|
///
|
|
|
|
/// handler.join().unwrap();
|
|
|
|
/// ```
|
2021-10-31 03:37:32 +00:00
|
|
|
#[must_use]
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
pub fn current() -> Thread {
|
2015-04-15 19:27:05 +00:00
|
|
|
thread_info::current_thread().expect(
|
2020-07-10 15:59:25 +00:00
|
|
|
"use of std::thread::current() is not possible \
|
|
|
|
after the thread's local data has been destroyed",
|
2015-04-15 19:27:05 +00:00
|
|
|
)
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Cooperatively gives up a timeslice to the OS scheduler.
|
2016-12-21 17:05:11 +00:00
|
|
|
///
|
2021-07-06 19:50:42 +00:00
|
|
|
/// This calls the underlying OS scheduler's yield primitive, signaling
|
|
|
|
/// that the calling thread is willing to give up its remaining timeslice
|
|
|
|
/// so that the OS may schedule other threads on the CPU.
|
|
|
|
///
|
|
|
|
/// A drawback of yielding in a loop is that if the OS does not have any
|
|
|
|
/// other ready threads to run on the current CPU, the thread will effectively
|
|
|
|
/// busy-wait, which wastes CPU time and energy.
|
|
|
|
///
|
|
|
|
/// Therefore, when waiting for events of interest, a programmer's first
|
|
|
|
/// choice should be to use synchronization devices such as [`channel`]s,
|
|
|
|
/// [`Condvar`]s, [`Mutex`]es or [`join`] since these primitives are
|
|
|
|
/// implemented in a blocking manner, giving up the CPU until the event
|
|
|
|
/// of interest has occurred which avoids repeated yielding.
|
|
|
|
///
|
|
|
|
/// `yield_now` should thus be used only rarely, mostly in situations where
|
|
|
|
/// repeated polling is required because there is no other suitable way to
|
|
|
|
/// learn when an event of interest has occurred.
|
2017-05-13 19:42:51 +00:00
|
|
|
///
|
2016-12-21 17:05:11 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// thread::yield_now();
|
|
|
|
/// ```
|
2017-05-13 19:42:51 +00:00
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`channel`]: crate::sync::mpsc
|
|
|
|
/// [`join`]: JoinHandle::join
|
2020-09-19 10:42:14 +00:00
|
|
|
/// [`Condvar`]: crate::sync::Condvar
|
|
|
|
/// [`Mutex`]: crate::sync::Mutex
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
pub fn yield_now() {
|
2015-04-15 05:13:57 +00:00
|
|
|
imp::Thread::yield_now()
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Determines whether the current thread is unwinding because of panic.
|
2016-06-16 21:11:17 +00:00
|
|
|
///
|
2017-05-07 14:49:18 +00:00
|
|
|
/// A common use of this feature is to poison shared resources when writing
|
|
|
|
/// unsafe code, by checking `panicking` when the `drop` is called.
|
|
|
|
///
|
|
|
|
/// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
|
|
|
|
/// already poison themselves when a thread panics while holding the lock.
|
|
|
|
///
|
|
|
|
/// This can also be used in multithreaded applications, in order to send a
|
2018-11-27 02:59:49 +00:00
|
|
|
/// message to other threads warning that a thread has panicked (e.g., for
|
2017-05-07 14:49:18 +00:00
|
|
|
/// monitoring purposes).
|
|
|
|
///
|
2016-06-16 21:11:17 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
2016-12-21 17:05:11 +00:00
|
|
|
/// ```should_panic
|
2016-06-16 21:11:17 +00:00
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// struct SomeStruct;
|
|
|
|
///
|
|
|
|
/// impl Drop for SomeStruct {
|
|
|
|
/// fn drop(&mut self) {
|
|
|
|
/// if thread::panicking() {
|
|
|
|
/// println!("dropped while unwinding");
|
|
|
|
/// } else {
|
|
|
|
/// println!("dropped while not unwinding");
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// {
|
|
|
|
/// print!("a: ");
|
|
|
|
/// let a = SomeStruct;
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// {
|
|
|
|
/// print!("b: ");
|
|
|
|
/// let b = SomeStruct;
|
|
|
|
/// panic!()
|
|
|
|
/// }
|
|
|
|
/// ```
|
2020-09-19 10:42:14 +00:00
|
|
|
///
|
|
|
|
/// [Mutex]: crate::sync::Mutex
|
2015-02-17 09:08:53 +00:00
|
|
|
#[inline]
|
2021-10-31 03:37:32 +00:00
|
|
|
#[must_use]
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
pub fn panicking() -> bool {
|
rustc: Implement custom panic runtimes
This commit is an implementation of [RFC 1513] which allows applications to
alter the behavior of panics at compile time. A new compiler flag, `-C panic`,
is added and accepts the values `unwind` or `panic`, with the default being
`unwind`. This model affects how code is generated for the local crate, skipping
generation of landing pads with `-C panic=abort`.
[RFC 1513]: https://github.com/rust-lang/rfcs/blob/master/text/1513-less-unwinding.md
Panic implementations are then provided by crates tagged with
`#![panic_runtime]` and lazily required by crates with
`#![needs_panic_runtime]`. The panic strategy (`-C panic` value) of the panic
runtime must match the final product, and if the panic strategy is not `abort`
then the entire DAG must have the same panic strategy.
With the `-C panic=abort` strategy, users can expect a stable method to disable
generation of landing pads, improving optimization in niche scenarios,
decreasing compile time, and decreasing output binary size. With the `-C
panic=unwind` strategy users can expect the existing ability to isolate failure
in Rust code from the outside world.
Organizationally, this commit dismantles the `sys_common::unwind` module in
favor of some bits moving part of it to `libpanic_unwind` and the rest into the
`panicking` module in libstd. The custom panic runtime support is pretty similar
to the custom allocator support with the only major difference being how the
panic runtime is injected (takes the `-C panic` flag into account).
2016-04-08 23:18:40 +00:00
|
|
|
panicking::panicking()
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
|
2018-09-28 19:40:20 +00:00
|
|
|
/// Puts the current thread to sleep for at least the specified amount of time.
|
2015-03-13 03:36:31 +00:00
|
|
|
///
|
|
|
|
/// The thread may sleep longer than the duration specified due to scheduling
|
2018-09-28 19:40:20 +00:00
|
|
|
/// specifics or platform-dependent functionality. It will never sleep less.
|
2017-01-01 19:53:18 +00:00
|
|
|
///
|
2020-05-12 15:38:02 +00:00
|
|
|
/// This function is blocking, and should not be used in `async` functions.
|
|
|
|
///
|
2018-02-18 01:54:26 +00:00
|
|
|
/// # Platform-specific behavior
|
2017-01-01 19:53:18 +00:00
|
|
|
///
|
2018-10-11 18:37:30 +00:00
|
|
|
/// On Unix platforms, the underlying syscall may be interrupted by a
|
|
|
|
/// spurious wakeup or signal handler. To ensure the sleep occurs for at least
|
|
|
|
/// the specified duration, this function may invoke that system call multiple
|
|
|
|
/// times.
|
2016-12-21 17:05:11 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```no_run
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// // Let's sleep for 2 seconds:
|
|
|
|
/// thread::sleep_ms(2000);
|
|
|
|
/// ```
|
2015-04-01 19:20:57 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2022-04-08 01:20:32 +00:00
|
|
|
#[deprecated(since = "1.6.0", note = "replaced by `std::thread::sleep`")]
|
2015-04-01 19:20:57 +00:00
|
|
|
pub fn sleep_ms(ms: u32) {
|
2015-04-28 18:40:04 +00:00
|
|
|
sleep(Duration::from_millis(ms as u64))
|
|
|
|
}
|
|
|
|
|
2018-10-01 08:01:15 +00:00
|
|
|
/// Puts the current thread to sleep for at least the specified amount of time.
|
2015-04-28 18:40:04 +00:00
|
|
|
///
|
|
|
|
/// The thread may sleep longer than the duration specified due to scheduling
|
2018-10-01 08:01:15 +00:00
|
|
|
/// specifics or platform-dependent functionality. It will never sleep less.
|
2015-04-28 18:40:04 +00:00
|
|
|
///
|
2020-05-12 15:38:02 +00:00
|
|
|
/// This function is blocking, and should not be used in `async` functions.
|
|
|
|
///
|
2018-02-18 01:54:26 +00:00
|
|
|
/// # Platform-specific behavior
|
2015-04-28 18:40:04 +00:00
|
|
|
///
|
2018-10-11 18:37:30 +00:00
|
|
|
/// On Unix platforms, the underlying syscall may be interrupted by a
|
|
|
|
/// spurious wakeup or signal handler. To ensure the sleep occurs for at least
|
|
|
|
/// the specified duration, this function may invoke that system call multiple
|
|
|
|
/// times.
|
2018-10-01 08:01:15 +00:00
|
|
|
/// Platforms which do not support nanosecond precision for sleeping will
|
|
|
|
/// have `dur` rounded up to the nearest granularity of time they can sleep for.
|
2016-06-22 01:41:02 +00:00
|
|
|
///
|
2020-12-23 00:07:48 +00:00
|
|
|
/// Currently, specifying a zero duration on Unix platforms returns immediately
|
|
|
|
/// without invoking the underlying [`nanosleep`] syscall, whereas on Windows
|
|
|
|
/// platforms the underlying [`Sleep`] syscall is always invoked.
|
|
|
|
/// If the intention is to yield the current time-slice you may want to use
|
|
|
|
/// [`yield_now`] instead.
|
2021-01-15 21:41:26 +00:00
|
|
|
///
|
2020-12-23 00:07:48 +00:00
|
|
|
/// [`nanosleep`]: https://linux.die.net/man/2/nanosleep
|
|
|
|
/// [`Sleep`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
|
|
|
|
///
|
2016-06-22 01:41:02 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
2016-12-21 17:05:11 +00:00
|
|
|
/// ```no_run
|
2016-06-22 01:41:02 +00:00
|
|
|
/// use std::{thread, time};
|
|
|
|
///
|
|
|
|
/// let ten_millis = time::Duration::from_millis(10);
|
|
|
|
/// let now = time::Instant::now();
|
|
|
|
///
|
|
|
|
/// thread::sleep(ten_millis);
|
|
|
|
///
|
|
|
|
/// assert!(now.elapsed() >= ten_millis);
|
|
|
|
/// ```
|
2015-09-10 20:26:44 +00:00
|
|
|
#[stable(feature = "thread_sleep", since = "1.4.0")]
|
2015-04-28 18:40:04 +00:00
|
|
|
pub fn sleep(dur: Duration) {
|
|
|
|
imp::Thread::sleep(dur)
|
2015-04-01 19:20:57 +00:00
|
|
|
}
|
|
|
|
|
2015-07-07 13:35:56 +00:00
|
|
|
/// Blocks unless or until the current thread's token is made available.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
2017-05-07 16:55:20 +00:00
|
|
|
/// A call to `park` does not guarantee that the thread will remain parked
|
|
|
|
/// forever, and callers should be prepared for this possibility.
|
|
|
|
///
|
|
|
|
/// # park and unpark
|
|
|
|
///
|
|
|
|
/// Every thread is equipped with some basic low-level blocking support, via the
|
2017-05-07 19:43:46 +00:00
|
|
|
/// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
|
2017-05-07 16:55:20 +00:00
|
|
|
/// method. [`park`] blocks the current thread, which can then be resumed from
|
|
|
|
/// another thread by calling the [`unpark`] method on the blocked thread's
|
|
|
|
/// handle.
|
|
|
|
///
|
|
|
|
/// Conceptually, each [`Thread`] handle has an associated token, which is
|
|
|
|
/// initially not present:
|
2015-07-07 13:35:56 +00:00
|
|
|
///
|
2017-05-07 16:55:20 +00:00
|
|
|
/// * The [`thread::park`][`park`] function blocks the current thread unless or
|
|
|
|
/// until the token is available for its thread handle, at which point it
|
|
|
|
/// atomically consumes the token. It may also return *spuriously*, without
|
|
|
|
/// consuming the token. [`thread::park_timeout`] does the same, but allows
|
|
|
|
/// specifying a maximum time to block the thread for.
|
|
|
|
///
|
|
|
|
/// * The [`unpark`] method on a [`Thread`] atomically makes the token available
|
2018-07-27 11:44:20 +00:00
|
|
|
/// if it wasn't already. Because the token is initially absent, [`unpark`]
|
2018-07-27 11:01:42 +00:00
|
|
|
/// followed by [`park`] will result in the second call returning immediately.
|
2015-07-07 13:35:56 +00:00
|
|
|
///
|
2017-05-07 16:55:20 +00:00
|
|
|
/// In other words, each [`Thread`] acts a bit like a spinlock that can be
|
|
|
|
/// locked and unlocked using `park` and `unpark`.
|
2015-07-07 13:35:56 +00:00
|
|
|
///
|
2018-12-03 14:14:31 +00:00
|
|
|
/// Notice that being unblocked does not imply any synchronization with someone
|
|
|
|
/// that unparked this thread, it could also be spurious.
|
|
|
|
/// For example, it would be a valid, but inefficient, implementation to make both [`park`] and
|
|
|
|
/// [`unpark`] return immediately without doing anything.
|
2018-11-22 09:54:04 +00:00
|
|
|
///
|
2015-07-07 13:35:56 +00:00
|
|
|
/// The API is typically used by acquiring a handle to the current thread,
|
|
|
|
/// placing that handle in a shared data structure so that other threads can
|
2018-11-22 09:54:04 +00:00
|
|
|
/// find it, and then `park`ing in a loop. When some desired condition is met, another
|
2017-05-07 16:55:20 +00:00
|
|
|
/// thread calls [`unpark`] on the handle.
|
2015-07-07 13:35:56 +00:00
|
|
|
///
|
2017-05-07 16:55:20 +00:00
|
|
|
/// The motivation for this design is twofold:
|
|
|
|
///
|
|
|
|
/// * It avoids the need to allocate mutexes and condvars when building new
|
|
|
|
/// synchronization primitives; the threads already provide basic
|
|
|
|
/// blocking/signaling.
|
2015-07-07 13:35:56 +00:00
|
|
|
///
|
2017-05-07 16:55:20 +00:00
|
|
|
/// * It can be implemented very efficiently on many platforms.
|
2015-07-07 13:35:56 +00:00
|
|
|
///
|
2017-05-07 16:55:20 +00:00
|
|
|
/// # Examples
|
2015-07-07 13:35:56 +00:00
|
|
|
///
|
2017-05-07 16:55:20 +00:00
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
2018-11-23 10:04:16 +00:00
|
|
|
/// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
|
2017-05-07 19:43:46 +00:00
|
|
|
/// use std::time::Duration;
|
2017-05-07 16:55:20 +00:00
|
|
|
///
|
2018-11-23 10:04:16 +00:00
|
|
|
/// let flag = Arc::new(AtomicBool::new(false));
|
|
|
|
/// let flag2 = Arc::clone(&flag);
|
|
|
|
///
|
|
|
|
/// let parked_thread = thread::spawn(move || {
|
2019-02-09 21:23:30 +00:00
|
|
|
/// // We want to wait until the flag is set. We *could* just spin, but using
|
2018-11-23 10:04:16 +00:00
|
|
|
/// // park/unpark is more efficient.
|
|
|
|
/// while !flag2.load(Ordering::Acquire) {
|
2017-05-07 16:55:20 +00:00
|
|
|
/// println!("Parking thread");
|
|
|
|
/// thread::park();
|
2018-11-22 09:54:04 +00:00
|
|
|
/// // We *could* get here spuriously, i.e., way before the 10ms below are over!
|
2018-11-23 10:04:16 +00:00
|
|
|
/// // But that is no problem, we are in a loop until the flag is set anyway.
|
2017-05-07 16:55:20 +00:00
|
|
|
/// println!("Thread unparked");
|
2018-11-23 10:04:16 +00:00
|
|
|
/// }
|
|
|
|
/// println!("Flag received");
|
|
|
|
/// });
|
2017-05-07 16:55:20 +00:00
|
|
|
///
|
|
|
|
/// // Let some time pass for the thread to be spawned.
|
|
|
|
/// thread::sleep(Duration::from_millis(10));
|
|
|
|
///
|
2018-11-23 10:04:16 +00:00
|
|
|
/// // Set the flag, and let the thread wake up.
|
2018-07-27 11:01:42 +00:00
|
|
|
/// // There is no race condition here, if `unpark`
|
|
|
|
/// // happens first, `park` will return immediately.
|
2018-11-23 10:04:16 +00:00
|
|
|
/// // Hence there is no risk of a deadlock.
|
|
|
|
/// flag.store(true, Ordering::Release);
|
2017-05-07 16:55:20 +00:00
|
|
|
/// println!("Unpark the thread");
|
|
|
|
/// parked_thread.thread().unpark();
|
|
|
|
///
|
|
|
|
/// parked_thread.join().unwrap();
|
|
|
|
/// ```
|
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`unpark`]: Thread::unpark
|
|
|
|
/// [`thread::park_timeout`]: park_timeout
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
pub fn park() {
|
2020-09-19 10:42:14 +00:00
|
|
|
// SAFETY: park_timeout is called on the parker owned by this thread.
|
|
|
|
unsafe {
|
2022-04-25 13:19:50 +00:00
|
|
|
current().inner.as_ref().parker().park();
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-09 17:02:43 +00:00
|
|
|
/// Use [`park_timeout`].
|
2016-08-03 11:34:49 +00:00
|
|
|
///
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Blocks unless or until the current thread's token is made available or
|
2015-02-17 09:08:53 +00:00
|
|
|
/// the specified duration has been reached (may wake spuriously).
|
|
|
|
///
|
2017-05-09 17:02:43 +00:00
|
|
|
/// The semantics of this function are equivalent to [`park`] except
|
2017-05-07 11:47:39 +00:00
|
|
|
/// that the thread will be blocked for roughly no longer than `dur`. This
|
|
|
|
/// method should not be used for precise timing due to anomalies such as
|
2021-07-23 23:14:28 +00:00
|
|
|
/// preemption or platform differences that might not cause the maximum
|
2016-06-22 12:24:16 +00:00
|
|
|
/// amount of time waited to be precisely `ms` long.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
2017-05-09 17:02:43 +00:00
|
|
|
/// See the [park documentation][`park`] for more detail.
|
2015-04-01 19:20:57 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2022-04-08 01:20:32 +00:00
|
|
|
#[deprecated(since = "1.6.0", note = "replaced by `std::thread::park_timeout`")]
|
2015-04-01 19:20:57 +00:00
|
|
|
pub fn park_timeout_ms(ms: u32) {
|
2015-04-28 18:40:04 +00:00
|
|
|
park_timeout(Duration::from_millis(ms as u64))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Blocks unless or until the current thread's token is made available or
|
|
|
|
/// the specified duration has been reached (may wake spuriously).
|
|
|
|
///
|
2017-05-07 19:43:46 +00:00
|
|
|
/// The semantics of this function are equivalent to [`park`][park] except
|
2017-05-07 11:47:39 +00:00
|
|
|
/// that the thread will be blocked for roughly no longer than `dur`. This
|
|
|
|
/// method should not be used for precise timing due to anomalies such as
|
2021-07-23 23:14:28 +00:00
|
|
|
/// preemption or platform differences that might not cause the maximum
|
2016-06-22 12:24:16 +00:00
|
|
|
/// amount of time waited to be precisely `dur` long.
|
2015-04-28 18:40:04 +00:00
|
|
|
///
|
2017-07-23 15:06:16 +00:00
|
|
|
/// See the [park documentation][park] for more details.
|
2015-04-28 18:40:04 +00:00
|
|
|
///
|
2018-02-18 01:54:26 +00:00
|
|
|
/// # Platform-specific behavior
|
2015-04-28 18:40:04 +00:00
|
|
|
///
|
|
|
|
/// Platforms which do not support nanosecond precision for sleeping will have
|
|
|
|
/// `dur` rounded up to the nearest granularity of time they can sleep for.
|
2016-08-03 11:30:28 +00:00
|
|
|
///
|
2017-08-24 15:33:36 +00:00
|
|
|
/// # Examples
|
2016-08-03 11:30:28 +00:00
|
|
|
///
|
|
|
|
/// Waiting for the complete expiration of the timeout:
|
|
|
|
///
|
|
|
|
/// ```rust,no_run
|
|
|
|
/// use std::thread::park_timeout;
|
|
|
|
/// use std::time::{Instant, Duration};
|
|
|
|
///
|
|
|
|
/// let timeout = Duration::from_secs(2);
|
|
|
|
/// let beginning_park = Instant::now();
|
|
|
|
///
|
2017-06-12 04:03:25 +00:00
|
|
|
/// let mut timeout_remaining = timeout;
|
|
|
|
/// loop {
|
|
|
|
/// park_timeout(timeout_remaining);
|
|
|
|
/// let elapsed = beginning_park.elapsed();
|
|
|
|
/// if elapsed >= timeout {
|
|
|
|
/// break;
|
|
|
|
/// }
|
2022-02-12 19:16:17 +00:00
|
|
|
/// println!("restarting park_timeout after {elapsed:?}");
|
2017-06-12 04:03:25 +00:00
|
|
|
/// timeout_remaining = timeout - elapsed;
|
2016-08-03 11:30:28 +00:00
|
|
|
/// }
|
|
|
|
/// ```
|
2015-09-10 20:26:44 +00:00
|
|
|
#[stable(feature = "park_timeout", since = "1.4.0")]
|
2015-04-28 18:40:04 +00:00
|
|
|
pub fn park_timeout(dur: Duration) {
|
2020-09-19 10:42:14 +00:00
|
|
|
// SAFETY: park_timeout is called on the parker owned by this thread.
|
|
|
|
unsafe {
|
2022-04-25 13:19:50 +00:00
|
|
|
current().inner.as_ref().parker().park_timeout(dur);
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-08 04:48:07 +00:00
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// ThreadId
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
|
|
|
/// A unique identifier for a running thread.
|
|
|
|
///
|
2021-04-11 08:35:00 +00:00
|
|
|
/// A `ThreadId` is an opaque object that uniquely identifies each thread
|
|
|
|
/// created during the lifetime of a process. `ThreadId`s are guaranteed not to
|
2021-12-25 15:18:55 +00:00
|
|
|
/// be reused, even when a thread terminates. `ThreadId`s are under the control
|
|
|
|
/// of Rust's standard library and there may not be any relationship between
|
2021-04-11 08:35:00 +00:00
|
|
|
/// `ThreadId` and the underlying platform's notion of a thread identifier --
|
|
|
|
/// the two concepts cannot, therefore, be used interchangeably. A `ThreadId`
|
|
|
|
/// can be retrieved from the [`id`] method on a [`Thread`].
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
2017-04-02 03:17:59 +00:00
|
|
|
/// let other_thread = thread::spawn(|| {
|
|
|
|
/// thread::current().id()
|
|
|
|
/// });
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
2017-04-02 03:17:59 +00:00
|
|
|
/// let other_thread_id = other_thread.join().unwrap();
|
|
|
|
/// assert!(thread::current().id() != other_thread_id);
|
2016-12-22 15:50:34 +00:00
|
|
|
/// ```
|
2017-08-03 00:59:33 +00:00
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`id`]: Thread::id
|
2017-06-08 15:41:23 +00:00
|
|
|
#[stable(feature = "thread_id", since = "1.19.0")]
|
2017-04-04 15:44:57 +00:00
|
|
|
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
|
2019-03-19 12:59:38 +00:00
|
|
|
pub struct ThreadId(NonZeroU64);
|
2016-09-08 04:48:07 +00:00
|
|
|
|
|
|
|
impl ThreadId {
|
2016-10-05 23:11:28 +00:00
|
|
|
// Generate a new unique thread ID.
|
2016-10-05 16:34:25 +00:00
|
|
|
fn new() -> ThreadId {
|
2022-08-01 12:32:09 +00:00
|
|
|
#[cold]
|
|
|
|
fn exhausted() -> ! {
|
|
|
|
panic!("failed to generate unique thread ID: bitspace exhausted")
|
|
|
|
}
|
2016-10-05 16:34:25 +00:00
|
|
|
|
2022-08-01 12:32:09 +00:00
|
|
|
cfg_if::cfg_if! {
|
|
|
|
if #[cfg(target_has_atomic = "64")] {
|
|
|
|
use crate::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
2016-09-08 04:48:07 +00:00
|
|
|
|
2022-08-01 12:32:09 +00:00
|
|
|
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
|
|
|
|
|
|
|
let mut last = COUNTER.load(Relaxed);
|
|
|
|
loop {
|
|
|
|
let Some(id) = last.checked_add(1) else {
|
|
|
|
exhausted();
|
|
|
|
};
|
|
|
|
|
|
|
|
match COUNTER.compare_exchange_weak(last, id, Relaxed, Relaxed) {
|
|
|
|
Ok(_) => return ThreadId(NonZeroU64::new(id).unwrap()),
|
|
|
|
Err(id) => last = id,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
use crate::sys_common::mutex::StaticMutex;
|
2016-10-05 16:34:25 +00:00
|
|
|
|
2022-08-01 12:32:09 +00:00
|
|
|
// It is UB to attempt to acquire this mutex reentrantly!
|
|
|
|
static GUARD: StaticMutex = StaticMutex::new();
|
|
|
|
static mut COUNTER: u64 = 0;
|
2016-10-05 16:34:25 +00:00
|
|
|
|
2022-08-01 12:32:09 +00:00
|
|
|
unsafe {
|
|
|
|
let guard = GUARD.lock();
|
|
|
|
|
|
|
|
let Some(id) = COUNTER.checked_add(1) else {
|
|
|
|
drop(guard); // in case the panic handler ends up calling `ThreadId::new()`, avoid reentrant lock acquire.
|
|
|
|
exhausted();
|
|
|
|
};
|
|
|
|
|
|
|
|
COUNTER = id;
|
|
|
|
drop(guard);
|
|
|
|
ThreadId(NonZeroU64::new(id).unwrap())
|
|
|
|
}
|
|
|
|
}
|
2016-10-05 23:11:28 +00:00
|
|
|
}
|
2016-09-08 04:48:07 +00:00
|
|
|
}
|
2019-12-23 17:54:54 +00:00
|
|
|
|
|
|
|
/// This returns a numeric identifier for the thread identified by this
|
|
|
|
/// `ThreadId`.
|
|
|
|
///
|
|
|
|
/// As noted in the documentation for the type itself, it is essentially an
|
|
|
|
/// opaque ID, but is guaranteed to be unique for each thread. The returned
|
|
|
|
/// value is entirely opaque -- only equality testing is stable. Note that
|
|
|
|
/// it is not guaranteed which values new threads will return, and this may
|
|
|
|
/// change across Rust versions.
|
2021-10-11 17:57:38 +00:00
|
|
|
#[must_use]
|
2019-12-23 17:54:54 +00:00
|
|
|
#[unstable(feature = "thread_id_value", issue = "67939")]
|
2020-03-21 18:48:23 +00:00
|
|
|
pub fn as_u64(&self) -> NonZeroU64 {
|
|
|
|
self.0
|
2019-12-23 17:54:54 +00:00
|
|
|
}
|
2016-09-08 04:48:07 +00:00
|
|
|
}
|
|
|
|
|
2015-03-20 07:46:13 +00:00
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Thread
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2015-02-17 09:08:53 +00:00
|
|
|
/// The internal representation of a `Thread` handle
|
2014-11-25 16:52:10 +00:00
|
|
|
struct Inner {
|
2016-03-25 04:46:45 +00:00
|
|
|
name: Option<CString>, // Guaranteed to be UTF-8
|
2016-10-05 16:34:25 +00:00
|
|
|
id: ThreadId,
|
2020-09-19 10:42:14 +00:00
|
|
|
parker: Parker,
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
2022-04-25 13:19:50 +00:00
|
|
|
impl Inner {
|
|
|
|
fn parker(self: Pin<&Self>) -> Pin<&Parker> {
|
|
|
|
unsafe { Pin::map_unchecked(self, |inner| &inner.parker) }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-04 03:54:18 +00:00
|
|
|
#[derive(Clone)]
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2017-04-26 16:54:17 +00:00
|
|
|
/// A handle to a thread.
|
|
|
|
///
|
2017-05-07 17:26:32 +00:00
|
|
|
/// Threads are represented via the `Thread` type, which you can get in one of
|
|
|
|
/// two ways:
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
2018-11-27 02:59:49 +00:00
|
|
|
/// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
|
2017-05-07 17:26:32 +00:00
|
|
|
/// function, and calling [`thread`][`JoinHandle::thread`] on the
|
|
|
|
/// [`JoinHandle`].
|
|
|
|
/// * By requesting the current thread, using the [`thread::current`] function.
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
2017-05-07 17:26:32 +00:00
|
|
|
/// The [`thread::current`] function is available even for threads not spawned
|
|
|
|
/// by the APIs of this module.
|
|
|
|
///
|
2017-07-23 15:06:16 +00:00
|
|
|
/// There is usually no need to create a `Thread` struct yourself, one
|
2017-05-07 17:26:32 +00:00
|
|
|
/// should instead use a function like `spawn` to create new threads, see the
|
|
|
|
/// docs of [`Builder`] and [`spawn`] for more details.
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`thread::current`]: current
|
2014-11-25 16:52:10 +00:00
|
|
|
pub struct Thread {
|
2022-04-25 13:19:50 +00:00
|
|
|
inner: Pin<Arc<Inner>>,
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Thread {
|
2014-12-14 08:05:32 +00:00
|
|
|
// Used only internally to construct a thread object without spawning
|
2017-09-17 08:19:11 +00:00
|
|
|
// Panics if the name contains nuls.
|
2021-09-16 12:41:09 +00:00
|
|
|
pub(crate) fn new(name: Option<CString>) -> Thread {
|
2022-07-15 03:57:46 +00:00
|
|
|
// We have to use `unsafe` here to construct the `Parker` in-place,
|
2022-04-25 13:19:50 +00:00
|
|
|
// which is required for the UNIX implementation.
|
|
|
|
//
|
|
|
|
// SAFETY: We pin the Arc immediately after creation, so its address never
|
|
|
|
// changes.
|
|
|
|
let inner = unsafe {
|
|
|
|
let mut arc = Arc::<Inner>::new_uninit();
|
|
|
|
let ptr = Arc::get_mut_unchecked(&mut arc).as_mut_ptr();
|
|
|
|
addr_of_mut!((*ptr).name).write(name);
|
|
|
|
addr_of_mut!((*ptr).id).write(ThreadId::new());
|
|
|
|
Parker::new(addr_of_mut!((*ptr).parker));
|
|
|
|
Pin::new_unchecked(arc.assume_init())
|
|
|
|
};
|
|
|
|
|
|
|
|
Thread { inner }
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Atomically makes the handle's token available if it is not already.
|
|
|
|
///
|
2017-05-07 11:54:06 +00:00
|
|
|
/// Every thread is equipped with some basic low-level blocking support, via
|
2017-05-07 19:43:46 +00:00
|
|
|
/// the [`park`][park] function and the `unpark()` method. These can be
|
2017-05-07 11:54:06 +00:00
|
|
|
/// used as a more CPU-efficient implementation of a spinlock.
|
|
|
|
///
|
2017-05-07 16:55:20 +00:00
|
|
|
/// See the [park documentation][park] for more details.
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
2017-05-07 19:43:46 +00:00
|
|
|
/// use std::time::Duration;
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
2017-05-07 14:01:47 +00:00
|
|
|
/// let parked_thread = thread::Builder::new()
|
2016-12-22 15:50:34 +00:00
|
|
|
/// .spawn(|| {
|
2017-05-07 14:01:47 +00:00
|
|
|
/// println!("Parking thread");
|
|
|
|
/// thread::park();
|
|
|
|
/// println!("Thread unparked");
|
2016-12-22 15:50:34 +00:00
|
|
|
/// })
|
|
|
|
/// .unwrap();
|
|
|
|
///
|
2017-05-07 14:01:47 +00:00
|
|
|
/// // Let some time pass for the thread to be spawned.
|
|
|
|
/// thread::sleep(Duration::from_millis(10));
|
|
|
|
///
|
|
|
|
/// println!("Unpark the thread");
|
|
|
|
/// parked_thread.thread().unpark();
|
|
|
|
///
|
|
|
|
/// parked_thread.join().unwrap();
|
2016-12-22 15:50:34 +00:00
|
|
|
/// ```
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2020-09-19 12:54:52 +00:00
|
|
|
#[inline]
|
2014-11-25 16:52:10 +00:00
|
|
|
pub fn unpark(&self) {
|
2022-04-25 13:19:50 +00:00
|
|
|
self.inner.as_ref().parker().unpark();
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
2016-10-05 16:34:25 +00:00
|
|
|
/// Gets the thread's unique identifier.
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
2017-04-02 03:17:59 +00:00
|
|
|
/// let other_thread = thread::spawn(|| {
|
|
|
|
/// thread::current().id()
|
|
|
|
/// });
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
2017-04-02 03:17:59 +00:00
|
|
|
/// let other_thread_id = other_thread.join().unwrap();
|
|
|
|
/// assert!(thread::current().id() != other_thread_id);
|
2016-12-22 15:50:34 +00:00
|
|
|
/// ```
|
2017-06-08 15:41:23 +00:00
|
|
|
#[stable(feature = "thread_id", since = "1.19.0")]
|
2021-10-31 03:37:32 +00:00
|
|
|
#[must_use]
|
2016-10-05 16:34:25 +00:00
|
|
|
pub fn id(&self) -> ThreadId {
|
|
|
|
self.inner.id
|
|
|
|
}
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Gets the thread's name.
|
2016-06-19 21:51:35 +00:00
|
|
|
///
|
2017-08-13 16:16:42 +00:00
|
|
|
/// For more information about named threads, see
|
|
|
|
/// [this module-level documentation][naming-threads].
|
|
|
|
///
|
2016-06-19 21:51:35 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// Threads by default have no name specified:
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new();
|
|
|
|
///
|
|
|
|
/// let handler = builder.spawn(|| {
|
|
|
|
/// assert!(thread::current().name().is_none());
|
|
|
|
/// }).unwrap();
|
|
|
|
///
|
|
|
|
/// handler.join().unwrap();
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Thread with a specified name:
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new()
|
|
|
|
/// .name("foo".into());
|
|
|
|
///
|
|
|
|
/// let handler = builder.spawn(|| {
|
|
|
|
/// assert_eq!(thread::current().name(), Some("foo"))
|
|
|
|
/// }).unwrap();
|
|
|
|
///
|
|
|
|
/// handler.join().unwrap();
|
|
|
|
/// ```
|
2017-08-13 16:16:42 +00:00
|
|
|
///
|
|
|
|
/// [naming-threads]: ./index.html#naming-threads
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2021-10-31 03:37:32 +00:00
|
|
|
#[must_use]
|
2014-11-25 16:52:10 +00:00
|
|
|
pub fn name(&self) -> Option<&str> {
|
2016-03-25 04:46:45 +00:00
|
|
|
self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
|
|
|
|
}
|
|
|
|
|
|
|
|
fn cname(&self) -> Option<&CStr> {
|
Fix clippy warnings
Fixes clippy::{cone_on_copy, filter_next, redundant_closure, single_char_pattern, len_zero,redundant_field_names, useless_format, identity_conversion, map_clone, into_iter_on_ref, needless_return, option_as_ref_deref, unused_unit, unnecessary_mut_passed}
2020-05-11 11:01:37 +00:00
|
|
|
self.inner.name.as_deref()
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
impl fmt::Debug for Thread {
|
2019-03-01 08:34:11 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2021-03-27 12:29:23 +00:00
|
|
|
f.debug_struct("Thread")
|
|
|
|
.field("id", &self.id())
|
|
|
|
.field("name", &self.name())
|
|
|
|
.finish_non_exhaustive()
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-20 07:46:13 +00:00
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
2015-08-13 17:12:38 +00:00
|
|
|
// JoinHandle
|
2015-03-20 07:46:13 +00:00
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2017-05-05 10:02:02 +00:00
|
|
|
/// A specialized [`Result`] type for threads.
|
2017-05-05 10:07:14 +00:00
|
|
|
///
|
2014-11-25 16:52:10 +00:00
|
|
|
/// Indicates the manner in which a thread exited.
|
|
|
|
///
|
2019-11-05 10:16:09 +00:00
|
|
|
/// The value contained in the `Result::Err` variant
|
|
|
|
/// is the value the thread panicked with;
|
2019-11-06 05:47:52 +00:00
|
|
|
/// that is, the argument the `panic!` macro was called with.
|
2019-11-05 10:16:09 +00:00
|
|
|
/// Unlike with normal errors, this value doesn't implement
|
2019-11-06 16:45:30 +00:00
|
|
|
/// the [`Error`](crate::error::Error) trait.
|
2019-11-05 10:16:09 +00:00
|
|
|
///
|
2019-11-06 05:47:52 +00:00
|
|
|
/// Thus, a sensible way to handle a thread panic is to either:
|
2020-12-18 22:03:45 +00:00
|
|
|
///
|
|
|
|
/// 1. propagate the panic with [`std::panic::resume_unwind`]
|
2019-11-06 05:47:52 +00:00
|
|
|
/// 2. or in case the thread is intended to be a subsystem boundary
|
2019-11-05 10:16:09 +00:00
|
|
|
/// that is supposed to isolate system-level failures,
|
2020-12-18 22:03:45 +00:00
|
|
|
/// match on the `Err` variant and handle the panic in an appropriate way
|
2019-11-05 10:16:09 +00:00
|
|
|
///
|
2014-11-25 16:52:10 +00:00
|
|
|
/// A thread that completes without panicking is considered to exit successfully.
|
2017-05-05 10:02:02 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
2020-12-18 22:03:45 +00:00
|
|
|
/// Matching on the result of a joined thread:
|
|
|
|
///
|
2017-05-05 10:02:02 +00:00
|
|
|
/// ```no_run
|
2020-12-18 22:03:45 +00:00
|
|
|
/// use std::{fs, thread, panic};
|
2017-05-05 10:02:02 +00:00
|
|
|
///
|
|
|
|
/// fn copy_in_thread() -> thread::Result<()> {
|
2020-12-18 22:03:45 +00:00
|
|
|
/// thread::spawn(|| {
|
|
|
|
/// fs::copy("foo.txt", "bar.txt").unwrap();
|
|
|
|
/// }).join()
|
2017-05-05 10:02:02 +00:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// match copy_in_thread() {
|
2020-12-18 22:03:45 +00:00
|
|
|
/// Ok(_) => println!("copy succeeded"),
|
|
|
|
/// Err(e) => panic::resume_unwind(e),
|
2017-05-05 10:02:02 +00:00
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`Result`]: crate::result::Result
|
2020-12-18 22:03:45 +00:00
|
|
|
/// [`std::panic::resume_unwind`]: crate::panic::resume_unwind
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-02-10 19:23:21 +00:00
|
|
|
pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2022-01-04 13:51:39 +00:00
|
|
|
// This packet is used to communicate the return value between the spawned
|
|
|
|
// thread and the rest of the program. It is shared through an `Arc` and
|
|
|
|
// there's no need for a mutex here because synchronization happens with `join()`
|
|
|
|
// (the caller will never read this packet until the thread has exited).
|
2015-04-15 05:13:57 +00:00
|
|
|
//
|
2022-01-04 13:51:39 +00:00
|
|
|
// An Arc to the packet is stored into a `JoinInner` which in turns is placed
|
2022-01-22 15:02:18 +00:00
|
|
|
// in `JoinHandle`.
|
2022-01-04 13:51:39 +00:00
|
|
|
struct Packet<'scope, T> {
|
2022-06-25 20:30:57 +00:00
|
|
|
scope: Option<Arc<scoped::ScopeData>>,
|
2022-01-04 13:51:39 +00:00
|
|
|
result: UnsafeCell<Option<Result<T>>>,
|
2022-06-25 20:30:57 +00:00
|
|
|
_marker: PhantomData<Option<&'scope scoped::ScopeData>>,
|
2022-01-04 13:51:39 +00:00
|
|
|
}
|
|
|
|
|
2022-01-22 15:02:18 +00:00
|
|
|
// Due to the usage of `UnsafeCell` we need to manually implement Sync.
|
|
|
|
// The type `T` should already always be Send (otherwise the thread could not
|
|
|
|
// have been created) and the Packet is Sync because all access to the
|
|
|
|
// `UnsafeCell` synchronized (by the `join()` boundary), and `ScopeData` is Sync.
|
2022-01-04 13:51:39 +00:00
|
|
|
unsafe impl<'scope, T: Sync> Sync for Packet<'scope, T> {}
|
|
|
|
|
|
|
|
impl<'scope, T> Drop for Packet<'scope, T> {
|
|
|
|
fn drop(&mut self) {
|
2022-03-05 17:07:20 +00:00
|
|
|
// If this packet was for a thread that ran in a scope, the thread
|
|
|
|
// panicked, and nobody consumed the panic payload, we make sure
|
|
|
|
// the scope function will panic.
|
|
|
|
let unhandled_panic = matches!(self.result.get_mut(), Some(Err(_)));
|
|
|
|
// Drop the result without causing unwinding.
|
|
|
|
// This is only relevant for threads that aren't join()ed, as
|
|
|
|
// join() will take the `result` and set it to None, such that
|
|
|
|
// there is nothing left to drop here.
|
|
|
|
// If this panics, we should handle that, because we're outside the
|
|
|
|
// outermost `catch_unwind` of our thread.
|
|
|
|
// We just abort in that case, since there's nothing else we can do.
|
|
|
|
// (And even if we tried to handle it somehow, we'd also need to handle
|
|
|
|
// the case where the panic payload we get out of it also panics on
|
|
|
|
// drop, and so on. See issue #86027.)
|
|
|
|
if let Err(_) = panic::catch_unwind(panic::AssertUnwindSafe(|| {
|
|
|
|
*self.result.get_mut() = None;
|
|
|
|
})) {
|
|
|
|
rtabort!("thread result panicked on drop");
|
|
|
|
}
|
2022-01-04 15:10:14 +00:00
|
|
|
// Book-keeping so the scope knows when it's done.
|
2022-06-25 20:30:57 +00:00
|
|
|
if let Some(scope) = &self.scope {
|
2022-03-05 16:19:04 +00:00
|
|
|
// Now that there will be no more user code running on this thread
|
|
|
|
// that can use 'scope, mark the thread as 'finished'.
|
2022-03-05 17:07:20 +00:00
|
|
|
// It's important we only do this after the `result` has been dropped,
|
|
|
|
// since dropping it might still use things it borrowed from 'scope.
|
2022-01-05 10:24:42 +00:00
|
|
|
scope.decrement_num_running_threads(unhandled_panic);
|
2022-01-04 13:51:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-12-22 16:15:51 +00:00
|
|
|
|
2015-08-13 17:12:38 +00:00
|
|
|
/// Inner representation for JoinHandle
|
2022-01-04 13:51:39 +00:00
|
|
|
struct JoinInner<'scope, T> {
|
2022-01-04 13:06:08 +00:00
|
|
|
native: imp::Thread,
|
2014-11-25 16:52:10 +00:00
|
|
|
thread: Thread,
|
2022-01-04 13:51:39 +00:00
|
|
|
packet: Arc<Packet<'scope, T>>,
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
|
2022-01-04 13:51:39 +00:00
|
|
|
impl<'scope, T> JoinInner<'scope, T> {
|
2022-01-04 13:06:08 +00:00
|
|
|
fn join(mut self) -> Result<T> {
|
|
|
|
self.native.join();
|
2022-01-04 13:51:39 +00:00
|
|
|
Arc::get_mut(&mut self.packet).unwrap().result.get_mut().take().unwrap()
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// An owned permission to join on a thread (block on its termination).
|
|
|
|
///
|
2017-05-13 19:19:13 +00:00
|
|
|
/// A `JoinHandle` *detaches* the associated thread when it is dropped, which
|
2021-12-20 17:30:29 +00:00
|
|
|
/// means that there is no longer any handle to the thread and no way to `join`
|
2017-05-13 19:19:13 +00:00
|
|
|
/// on it.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
2016-12-23 10:25:11 +00:00
|
|
|
/// Due to platform restrictions, it is not possible to [`Clone`] this
|
2017-05-13 19:19:13 +00:00
|
|
|
/// handle: the ability to join a thread is a uniquely-owned permission.
|
2016-06-23 22:16:37 +00:00
|
|
|
///
|
|
|
|
/// This `struct` is created by the [`thread::spawn`] function and the
|
|
|
|
/// [`thread::Builder::spawn`] method.
|
|
|
|
///
|
2016-06-24 12:12:58 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// Creation from [`thread::spawn`]:
|
|
|
|
///
|
2016-12-23 10:25:11 +00:00
|
|
|
/// ```
|
2016-06-24 12:12:58 +00:00
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
|
|
|
|
/// // some work here
|
|
|
|
/// });
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Creation from [`thread::Builder::spawn`]:
|
|
|
|
///
|
2016-12-23 10:25:11 +00:00
|
|
|
/// ```
|
2016-06-24 12:12:58 +00:00
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new();
|
|
|
|
///
|
|
|
|
/// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
|
|
|
|
/// // some work here
|
|
|
|
/// }).unwrap();
|
|
|
|
/// ```
|
|
|
|
///
|
2021-08-07 15:33:18 +00:00
|
|
|
/// A thread being detached and outliving the thread that spawned it:
|
2017-05-13 19:19:13 +00:00
|
|
|
///
|
|
|
|
/// ```no_run
|
|
|
|
/// use std::thread;
|
|
|
|
/// use std::time::Duration;
|
|
|
|
///
|
|
|
|
/// let original_thread = thread::spawn(|| {
|
|
|
|
/// let _detached_thread = thread::spawn(|| {
|
|
|
|
/// // Here we sleep to make sure that the first thread returns before.
|
|
|
|
/// thread::sleep(Duration::from_millis(10));
|
|
|
|
/// // This will be called, even though the JoinHandle is dropped.
|
|
|
|
/// println!("♫ Still alive ♫");
|
|
|
|
/// });
|
|
|
|
/// });
|
|
|
|
///
|
2017-10-01 18:55:58 +00:00
|
|
|
/// original_thread.join().expect("The thread being joined has panicked");
|
2017-05-13 19:19:13 +00:00
|
|
|
/// println!("Original thread is joined.");
|
|
|
|
///
|
|
|
|
/// // We make sure that the new thread has time to run, before the main
|
|
|
|
/// // thread returns.
|
|
|
|
///
|
|
|
|
/// thread::sleep(Duration::from_millis(1000));
|
|
|
|
/// ```
|
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`thread::Builder::spawn`]: Builder::spawn
|
|
|
|
/// [`thread::spawn`]: spawn
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2022-01-04 13:51:39 +00:00
|
|
|
pub struct JoinHandle<T>(JoinInner<'static, T>);
|
2015-02-17 09:08:53 +00:00
|
|
|
|
2018-07-27 08:08:02 +00:00
|
|
|
#[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
|
2018-07-26 23:08:13 +00:00
|
|
|
unsafe impl<T> Send for JoinHandle<T> {}
|
2018-07-27 08:08:02 +00:00
|
|
|
#[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
|
2018-07-26 23:08:13 +00:00
|
|
|
unsafe impl<T> Sync for JoinHandle<T> {}
|
|
|
|
|
2015-04-13 21:48:17 +00:00
|
|
|
impl<T> JoinHandle<T> {
|
2016-12-23 10:25:11 +00:00
|
|
|
/// Extracts a handle to the underlying thread.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new();
|
|
|
|
///
|
|
|
|
/// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
|
|
|
|
/// // some work here
|
|
|
|
/// }).unwrap();
|
|
|
|
///
|
|
|
|
/// let thread = join_handle.thread();
|
|
|
|
/// println!("thread id: {:?}", thread.id());
|
|
|
|
/// ```
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2021-10-31 03:37:32 +00:00
|
|
|
#[must_use]
|
2015-02-17 09:08:53 +00:00
|
|
|
pub fn thread(&self) -> &Thread {
|
|
|
|
&self.0.thread
|
|
|
|
}
|
|
|
|
|
2018-08-28 08:49:45 +00:00
|
|
|
/// Waits for the associated thread to finish.
|
|
|
|
///
|
2021-08-07 15:33:18 +00:00
|
|
|
/// This function will return immediately if the associated thread has already finished.
|
|
|
|
///
|
2018-08-28 08:49:45 +00:00
|
|
|
/// In terms of [atomic memory orderings], the completion of the associated
|
|
|
|
/// thread synchronizes with this function returning. In other words, all
|
2021-08-07 15:33:18 +00:00
|
|
|
/// operations performed by that thread [happen
|
|
|
|
/// before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) all
|
2018-08-15 13:22:54 +00:00
|
|
|
/// operations that happen after `join` returns.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
2021-08-07 15:33:18 +00:00
|
|
|
/// If the associated thread panics, [`Err`] is returned with the parameter given
|
2020-08-20 20:03:00 +00:00
|
|
|
/// to [`panic!`].
|
2016-12-23 10:25:11 +00:00
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`Err`]: crate::result::Result::Err
|
|
|
|
/// [atomic memory orderings]: crate::sync::atomic
|
2016-12-23 10:25:11 +00:00
|
|
|
///
|
2017-08-27 02:36:46 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// This function may panic on some platforms if a thread attempts to join
|
|
|
|
/// itself or otherwise may create a deadlock with joining threads.
|
|
|
|
///
|
2016-12-23 10:25:11 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let builder = thread::Builder::new();
|
|
|
|
///
|
|
|
|
/// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
|
|
|
|
/// // some work here
|
|
|
|
/// }).unwrap();
|
|
|
|
/// join_handle.join().expect("Couldn't join on the associated thread");
|
|
|
|
/// ```
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2022-01-04 13:06:08 +00:00
|
|
|
pub fn join(self) -> Result<T> {
|
2015-02-17 09:08:53 +00:00
|
|
|
self.0.join()
|
|
|
|
}
|
2021-10-31 14:02:38 +00:00
|
|
|
|
2022-03-03 10:19:50 +00:00
|
|
|
/// Checks if the associated thread has finished running its main function.
|
2021-10-31 14:02:38 +00:00
|
|
|
///
|
2022-02-15 22:51:24 +00:00
|
|
|
/// `is_finished` supports implementing a non-blocking join operation, by checking
|
|
|
|
/// `is_finished`, and calling `join` if it returns `true`. This function does not block. To
|
|
|
|
/// block while waiting on the thread to finish, use [`join`][Self::join].
|
|
|
|
///
|
2022-03-03 10:19:50 +00:00
|
|
|
/// This might return `true` for a brief moment after the thread's main
|
2021-10-31 14:02:38 +00:00
|
|
|
/// function has returned, but before the thread itself has stopped running.
|
2022-03-03 10:19:50 +00:00
|
|
|
/// However, once this returns `true`, [`join`][Self::join] can be expected
|
|
|
|
/// to return quickly, without blocking for any significant amount of time.
|
2022-03-20 02:53:26 +00:00
|
|
|
#[stable(feature = "thread_is_running", since = "1.61.0")]
|
2022-03-03 10:19:50 +00:00
|
|
|
pub fn is_finished(&self) -> bool {
|
|
|
|
Arc::strong_count(&self.0.packet) == 1
|
2021-10-31 14:02:38 +00:00
|
|
|
}
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
|
2015-10-29 20:54:09 +00:00
|
|
|
impl<T> AsInner<imp::Thread> for JoinHandle<T> {
|
|
|
|
fn as_inner(&self) -> &imp::Thread {
|
2022-01-04 13:06:08 +00:00
|
|
|
&self.0.native
|
2015-10-29 20:54:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
|
|
|
|
fn into_inner(self) -> imp::Thread {
|
2022-01-04 13:06:08 +00:00
|
|
|
self.0.native
|
2015-10-29 20:54:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-29 13:31:47 +00:00
|
|
|
#[stable(feature = "std_debug", since = "1.16.0")]
|
2016-11-25 18:21:49 +00:00
|
|
|
impl<T> fmt::Debug for JoinHandle<T> {
|
2019-03-01 08:34:11 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2021-04-05 11:31:11 +00:00
|
|
|
f.debug_struct("JoinHandle").finish_non_exhaustive()
|
2016-11-25 18:21:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-15 05:13:57 +00:00
|
|
|
fn _assert_sync_and_send() {
|
|
|
|
fn _assert_both<T: Send + Sync>() {}
|
|
|
|
_assert_both::<JoinHandle<()>>();
|
|
|
|
_assert_both::<Thread>();
|
|
|
|
}
|
2021-04-29 09:40:14 +00:00
|
|
|
|
2021-10-08 15:17:50 +00:00
|
|
|
/// Returns an estimate of the default amount of parallelism a program should use.
|
|
|
|
///
|
|
|
|
/// Parallelism is a resource. A given machine provides a certain capacity for
|
|
|
|
/// parallelism, i.e., a bound on the number of computations it can perform
|
2022-02-22 17:44:45 +00:00
|
|
|
/// simultaneously. This number often corresponds to the amount of CPUs a
|
2021-10-08 15:17:50 +00:00
|
|
|
/// computer has, but it may diverge in various cases.
|
|
|
|
///
|
|
|
|
/// Host environments such as VMs or container orchestrators may want to
|
|
|
|
/// restrict the amount of parallelism made available to programs in them. This
|
|
|
|
/// is often done to limit the potential impact of (unintentionally)
|
|
|
|
/// resource-intensive programs on other programs running on the same machine.
|
|
|
|
///
|
|
|
|
/// # Limitations
|
|
|
|
///
|
|
|
|
/// The purpose of this API is to provide an easy and portable way to query
|
|
|
|
/// the default amount of parallelism the program should use. Among other things it
|
|
|
|
/// does not expose information on NUMA regions, does not account for
|
2021-11-19 21:52:09 +00:00
|
|
|
/// differences in (co)processor capabilities or current system load,
|
|
|
|
/// and will not modify the program's global state in order to more accurately
|
|
|
|
/// query the amount of available parallelism.
|
|
|
|
///
|
|
|
|
/// Where both fixed steady-state and burst limits are available the steady-state
|
|
|
|
/// capacity will be used to ensure more predictable latencies.
|
2021-10-08 15:17:50 +00:00
|
|
|
///
|
2021-10-23 11:01:07 +00:00
|
|
|
/// Resource limits can be changed during the runtime of a program, therefore the value is
|
|
|
|
/// not cached and instead recomputed every time this function is called. It should not be
|
|
|
|
/// called from hot code.
|
|
|
|
///
|
2021-10-08 15:17:50 +00:00
|
|
|
/// The value returned by this function should be considered a simplified
|
|
|
|
/// approximation of the actual amount of parallelism available at any given
|
|
|
|
/// time. To get a more detailed or precise overview of the amount of
|
|
|
|
/// parallelism available to the program, you may wish to use
|
|
|
|
/// platform-specific APIs as well. The following platform limitations currently
|
|
|
|
/// apply to `available_parallelism`:
|
|
|
|
///
|
|
|
|
/// On Windows:
|
|
|
|
/// - It may undercount the amount of parallelism available on systems with more
|
|
|
|
/// than 64 logical CPUs. However, programs typically need specific support to
|
|
|
|
/// take advantage of more than 64 logical CPUs, and in the absence of such
|
|
|
|
/// support, the number returned by this function accurately reflects the
|
|
|
|
/// number of logical CPUs the program can use by default.
|
|
|
|
/// - It may overcount the amount of parallelism available on systems limited by
|
|
|
|
/// process-wide affinity masks, or job object limitations.
|
|
|
|
///
|
|
|
|
/// On Linux:
|
|
|
|
/// - It may overcount the amount of parallelism available when limited by a
|
2022-06-09 18:52:17 +00:00
|
|
|
/// process-wide affinity mask or cgroup quotas and `sched_getaffinity()` or cgroup fs can't be
|
2022-03-02 23:36:23 +00:00
|
|
|
/// queried, e.g. due to sandboxing.
|
|
|
|
/// - It may undercount the amount of parallelism if the current thread's affinity mask
|
|
|
|
/// does not reflect the process' cpuset, e.g. due to pinned threads.
|
2022-07-22 20:18:07 +00:00
|
|
|
/// - If the process is in a cgroup v1 cpu controller, this may need to
|
|
|
|
/// scan mountpoints to find the corresponding cgroup v1 controller,
|
|
|
|
/// which may take time on systems with large numbers of mountpoints.
|
|
|
|
/// (This does not apply to cgroup v2, or to processes not in a
|
|
|
|
/// cgroup.)
|
2021-10-08 15:17:50 +00:00
|
|
|
///
|
|
|
|
/// On all targets:
|
|
|
|
/// - It may overcount the amount of parallelism available when running in a VM
|
|
|
|
/// with CPU usage limits (e.g. an overcommitted host).
|
2021-04-29 09:40:14 +00:00
|
|
|
///
|
|
|
|
/// # Errors
|
|
|
|
///
|
2021-10-08 15:17:50 +00:00
|
|
|
/// This function will, but is not limited to, return errors in the following
|
|
|
|
/// cases:
|
2021-04-29 09:40:14 +00:00
|
|
|
///
|
2021-10-08 15:17:50 +00:00
|
|
|
/// - If the amount of parallelism is not known for the target platform.
|
|
|
|
/// - If the program lacks permission to query the amount of parallelism made
|
|
|
|
/// available to it.
|
2021-04-29 09:40:14 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # #![allow(dead_code)]
|
2021-10-08 15:17:50 +00:00
|
|
|
/// use std::{io, thread};
|
2021-04-29 09:40:14 +00:00
|
|
|
///
|
2021-10-08 15:17:50 +00:00
|
|
|
/// fn main() -> io::Result<()> {
|
|
|
|
/// let count = thread::available_parallelism()?.get();
|
|
|
|
/// assert!(count >= 1_usize);
|
|
|
|
/// Ok(())
|
|
|
|
/// }
|
2021-04-29 09:40:14 +00:00
|
|
|
/// ```
|
2021-10-08 15:17:50 +00:00
|
|
|
#[doc(alias = "available_concurrency")] // Alias for a previous name we gave this API on unstable.
|
2021-10-04 09:04:01 +00:00
|
|
|
#[doc(alias = "hardware_concurrency")] // Alias for C++ `std::thread::hardware_concurrency`.
|
2021-10-08 15:17:50 +00:00
|
|
|
#[doc(alias = "num_cpus")] // Alias for a popular ecosystem crate which provides similar functionality.
|
2022-01-07 00:04:37 +00:00
|
|
|
#[stable(feature = "available_parallelism", since = "1.59.0")]
|
2021-09-28 12:59:33 +00:00
|
|
|
pub fn available_parallelism() -> io::Result<NonZeroUsize> {
|
|
|
|
imp::available_parallelism()
|
2021-04-29 09:40:14 +00:00
|
|
|
}
|