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
|
2015-02-22 18:43:45 +00:00
|
|
|
//! child 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
|
|
|
//! ```
|
|
|
|
//!
|
2015-02-17 09:08:53 +00:00
|
|
|
//! In this example, the spawned thread is "detached" from the current
|
2015-02-22 18:43:45 +00:00
|
|
|
//! thread. This means that it can outlive its parent (the thread that spawned
|
|
|
|
//! it), unless this parent is the main thread.
|
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
|
|
|
//!
|
2015-04-13 21:48:17 +00:00
|
|
|
//! The parent thread can also wait on the completion of the child
|
2016-12-17 17:09:05 +00:00
|
|
|
//! thread; a call to [`spawn`] produces a [`JoinHandle`], which provides
|
2015-04-13 21:48:17 +00:00
|
|
|
//! a `join` method for waiting:
|
|
|
|
//!
|
|
|
|
//! ```rust
|
|
|
|
//! use std::thread;
|
|
|
|
//!
|
|
|
|
//! let child = thread::spawn(move || {
|
|
|
|
//! // some work here
|
|
|
|
//! });
|
|
|
|
//! // some work here
|
|
|
|
//! let res = child.join();
|
|
|
|
//! ```
|
|
|
|
//!
|
2017-05-04 09:11:14 +00:00
|
|
|
//! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
|
2016-12-17 17:09:05 +00:00
|
|
|
//! value produced by the child thread, or [`Err`] of the value given to
|
|
|
|
//! a call to [`panic!`] if the child panicked.
|
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,
|
2015-04-27 04:17:14 +00:00
|
|
|
//! which currently allows you to set the name and stack size for the child 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;
|
|
|
|
//!
|
2014-12-14 08:05:32 +00:00
|
|
|
//! thread::Builder::new().name("child1".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::name`]: Thread::name
|
|
|
|
//! [`thread::park_timeout`]: park_timeout
|
|
|
|
//! [`Cell`]: crate::cell::Cell
|
|
|
|
//! [`RefCell`]: crate::cell::RefCell
|
|
|
|
//! [`with`]: LocalKey::with
|
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;
|
|
|
|
|
2020-09-19 10:42:14 +00:00
|
|
|
mod parker;
|
|
|
|
|
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;
|
|
|
|
use crate::mem;
|
2019-03-19 12:59:38 +00:00
|
|
|
use crate::num::NonZeroU64;
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::panic;
|
|
|
|
use crate::panicking;
|
|
|
|
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::mutex;
|
|
|
|
use crate::sys_common::thread;
|
2019-12-22 22:42:04 +00:00
|
|
|
use crate::sys_common::thread_info;
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::sys_common::{AsInner, IntoInner};
|
|
|
|
use crate::time::Duration;
|
2020-09-19 10:42:14 +00:00
|
|
|
use parker::Parker;
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2015-03-20 07:46:13 +00:00
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Thread-local storage
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2019-12-22 22:42:04 +00:00
|
|
|
#[macro_use]
|
|
|
|
mod local;
|
2015-04-08 00:10:09 +00:00
|
|
|
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-12-22 22:42:04 +00:00
|
|
|
pub use self::local::{AccessError, LocalKey};
|
2015-04-08 00:10:09 +00:00
|
|
|
|
2016-10-04 18:00:27 +00:00
|
|
|
// The types used by the thread_local! macro to access TLS keys. Note that there
|
|
|
|
// are two types, the "OS" type and the "fast" type. The OS thread local key
|
|
|
|
// type is accessed via platform-specific API calls and is slow, while the fast
|
|
|
|
// key type is accessed via code generated via LLVM, where TLS keys are set up
|
|
|
|
// by the elf linker. Note that the OS TLS type is always available: on macOS
|
|
|
|
// the standard library is compiled with support for older platform versions
|
|
|
|
// where fast TLS was not available; end-user code is compiled with fast TLS
|
|
|
|
// where available, but both are needed.
|
|
|
|
|
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)]
|
2019-12-22 22:42:04 +00:00
|
|
|
#[doc(hidden)]
|
|
|
|
pub use self::local::fast::Key as __FastLocalKeyInner;
|
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "none")]
|
|
|
|
#[doc(hidden)]
|
|
|
|
pub use self::local::os::Key as __OsLocalKeyInner;
|
2019-12-21 11:16:18 +00:00
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "none")]
|
2019-12-22 22:42:04 +00:00
|
|
|
#[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
|
|
|
|
#[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
|
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 {
|
2019-12-22 22:42:04 +00:00
|
|
|
Builder { name: None, stack_size: None }
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
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
|
2015-02-17 09:08:53 +00:00
|
|
|
/// termination of the child thread, including recovering its panics.
|
|
|
|
///
|
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")]
|
2019-12-22 22:42:04 +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
|
|
|
|
/// termination of the child thread, including recovering its panics.
|
|
|
|
///
|
|
|
|
/// 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
|
|
|
|
///
|
|
|
|
/// The caller has to ensure that no references in the supplied thread closure
|
|
|
|
/// or its return type can outlive the spawned thread's lifetime. This can be
|
|
|
|
/// guaranteed in two ways:
|
|
|
|
///
|
|
|
|
/// - 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")]
|
2019-12-22 22:42:04 +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,
|
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
|
|
|
|
2014-11-25 16:52:10 +00:00
|
|
|
let my_thread = Thread::new(name);
|
|
|
|
let their_thread = my_thread.clone();
|
|
|
|
|
2019-12-22 22:42:04 +00:00
|
|
|
let my_packet: Arc<UnsafeCell<Option<Result<T>>>> = Arc::new(UnsafeCell::new(None));
|
2015-04-15 05:13:57 +00:00
|
|
|
let their_packet = my_packet.clone();
|
2015-02-17 09:08:53 +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-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).
|
|
|
|
unsafe { *their_packet.get() = Some(try_result) };
|
2014-11-25 16:52:10 +00:00
|
|
|
};
|
|
|
|
|
2015-10-19 00:01:55 +00:00
|
|
|
Ok(JoinHandle(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 {
|
|
|
|
Some(imp::Thread::new(
|
|
|
|
stack_size,
|
|
|
|
mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(
|
|
|
|
Box::new(main),
|
|
|
|
),
|
|
|
|
)?)
|
|
|
|
},
|
2015-02-17 09:08:53 +00:00
|
|
|
thread: my_thread,
|
2015-04-15 05:13:57 +00:00
|
|
|
packet: Packet(my_packet),
|
2015-10-19 00:01:55 +00:00
|
|
|
}))
|
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
|
|
|
///
|
2015-02-20 22:45:40 +00:00
|
|
|
/// The join handle will implicitly *detach* the child thread upon being
|
|
|
|
/// dropped. In this case, the child thread may outlive the parent (unless
|
|
|
|
/// the parent thread is the main thread; the whole process is terminated when
|
2016-12-21 17:05:11 +00:00
|
|
|
/// the main thread finishes). Additionally, the join handle provides a [`join`]
|
2015-02-20 22:45:40 +00:00
|
|
|
/// method that can be used to join the child thread. If the child thread
|
2016-12-21 17:05:11 +00:00
|
|
|
/// panics, [`join`] will return an [`Err`] containing the argument given to
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`panic!`].
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
2017-05-09 11:27:22 +00:00
|
|
|
/// This will create a thread using default parameters of [`Builder`], if you
|
|
|
|
/// 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
|
|
|
|
/// is that threads can `detach` and outlive the lifetime they have been
|
|
|
|
/// created in.
|
|
|
|
/// 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");
|
|
|
|
/// 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();
|
2017-05-09 17:06:56 +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")]
|
2019-12-22 22:42:04 +00:00
|
|
|
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
|
|
|
|
where
|
|
|
|
F: FnOnce() -> T,
|
|
|
|
F: Send + 'static,
|
|
|
|
T: Send + 'static,
|
2015-04-13 21:48:17 +00:00
|
|
|
{
|
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();
|
|
|
|
/// ```
|
2015-02-17 09:08:53 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
pub fn current() -> Thread {
|
2019-12-22 22:42:04 +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",
|
2019-12-22 22:42:04 +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
|
|
|
///
|
2017-05-13 19:42:51 +00:00
|
|
|
/// This is used when the programmer knows that the thread will have nothing
|
|
|
|
/// to do for some time, and thus avoid wasting computing time.
|
|
|
|
///
|
|
|
|
/// For example when polling on a resource, it is common to check that it is
|
|
|
|
/// available, and if not to yield in order to avoid busy waiting.
|
|
|
|
///
|
|
|
|
/// Thus the pattern of `yield`ing after a failed poll is rather common when
|
|
|
|
/// implementing low-level shared resources or synchronization primitives.
|
|
|
|
///
|
2018-10-06 17:09:54 +00:00
|
|
|
/// However programmers will usually prefer to use [`channel`]s, [`Condvar`]s,
|
2017-08-15 19:45:21 +00:00
|
|
|
/// [`Mutex`]es or [`join`] for their synchronization routines, as they avoid
|
2017-08-10 22:16:18 +00:00
|
|
|
/// thinking about thread scheduling.
|
2017-05-13 19:42:51 +00:00
|
|
|
///
|
|
|
|
/// Note that [`channel`]s for example are implemented using this primitive.
|
|
|
|
/// Indeed when you call `send` or `recv`, which are blocking, they will yield
|
|
|
|
/// if the channel is not available.
|
|
|
|
///
|
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]
|
|
|
|
#[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")]
|
2015-11-20 13:11:20 +00:00
|
|
|
#[rustc_deprecated(since = "1.6.0", reason = "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
|
|
|
///
|
|
|
|
/// # 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 {
|
|
|
|
current().inner.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
|
2015-02-17 09:08:53 +00:00
|
|
|
/// preemption or platform differences that may 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")]
|
2015-11-20 13:11:20 +00:00
|
|
|
#[rustc_deprecated(since = "1.6.0", reason = "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
|
2015-04-28 18:40:04 +00:00
|
|
|
/// preemption or platform differences that may 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;
|
|
|
|
/// }
|
|
|
|
/// println!("restarting park_timeout after {:?}", elapsed);
|
|
|
|
/// 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 {
|
|
|
|
current().inner.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.
|
|
|
|
///
|
|
|
|
/// A `ThreadId` is an opaque object that has a unique value for each thread
|
2017-04-02 03:17:59 +00:00
|
|
|
/// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
|
2017-08-03 00:59:33 +00:00
|
|
|
/// system-designated identifier. 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 {
|
2018-08-08 16:12:33 +00:00
|
|
|
// We never call `GUARD.init()`, so it is UB to attempt to
|
2018-08-06 12:39:55 +00:00
|
|
|
// acquire this mutex reentrantly!
|
2016-10-05 23:11:28 +00:00
|
|
|
static GUARD: mutex::Mutex = mutex::Mutex::new();
|
2019-03-19 12:59:38 +00:00
|
|
|
static mut COUNTER: u64 = 1;
|
2016-10-05 16:34:25 +00:00
|
|
|
|
2016-10-05 23:11:28 +00:00
|
|
|
unsafe {
|
2018-06-09 13:13:04 +00:00
|
|
|
let _guard = GUARD.lock();
|
2016-09-08 04:48:07 +00:00
|
|
|
|
2016-10-05 16:34:25 +00:00
|
|
|
// If we somehow use up all our bits, panic so that we're not
|
|
|
|
// covering up subtle bugs of IDs being reused.
|
2020-04-16 22:43:04 +00:00
|
|
|
if COUNTER == u64::MAX {
|
2016-10-05 16:34:25 +00:00
|
|
|
panic!("failed to generate unique thread ID: bitspace exhausted");
|
2016-09-08 04:48:07 +00:00
|
|
|
}
|
2016-10-05 16:34:25 +00:00
|
|
|
|
|
|
|
let id = COUNTER;
|
|
|
|
COUNTER += 1;
|
|
|
|
|
2019-03-19 12:59:38 +00:00
|
|
|
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.
|
|
|
|
#[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 {
|
2019-12-22 22:42:04 +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
|
|
|
}
|
|
|
|
|
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 {
|
|
|
|
inner: Arc<Inner>,
|
|
|
|
}
|
|
|
|
|
|
|
|
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.
|
2017-03-14 01:42:23 +00:00
|
|
|
pub(crate) fn new(name: Option<String>) -> Thread {
|
2019-12-22 22:42:04 +00:00
|
|
|
let cname =
|
|
|
|
name.map(|n| CString::new(n).expect("thread name may not contain interior null bytes"));
|
2014-11-25 16:52:10 +00:00
|
|
|
Thread {
|
2020-09-19 10:42:14 +00:00
|
|
|
inner: Arc::new(Inner { name: cname, id: ThreadId::new(), parker: Parker::new() }),
|
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")]
|
2014-11-25 16:52:10 +00:00
|
|
|
pub fn unpark(&self) {
|
2020-09-19 10:42:14 +00:00
|
|
|
self.inner.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")]
|
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")]
|
2014-11-25 16:52:10 +00:00
|
|
|
pub fn name(&self) -> Option<&str> {
|
2019-12-22 22:42:04 +00:00
|
|
|
self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
|
2016-03-25 04:46:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
2019-12-22 22:42:04 +00:00
|
|
|
f.debug_struct("Thread").field("id", &self.id()).field("name", &self.name()).finish()
|
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:
|
|
|
|
/// 1. `unwrap` the `Result<T>`, propagating the panic
|
|
|
|
/// 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,
|
2019-11-06 05:47:52 +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
|
|
|
|
///
|
|
|
|
/// ```no_run
|
|
|
|
/// use std::thread;
|
|
|
|
/// use std::fs;
|
|
|
|
///
|
|
|
|
/// fn copy_in_thread() -> thread::Result<()> {
|
|
|
|
/// thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// match copy_in_thread() {
|
|
|
|
/// Ok(_) => println!("this is fine"),
|
|
|
|
/// Err(_) => println!("thread panicked"),
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`Result`]: crate::result::Result
|
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
|
|
|
|
2015-04-15 05:13:57 +00:00
|
|
|
// This packet is used to communicate the return value between the child thread
|
|
|
|
// and the parent thread. Memory is shared through the `Arc` within and there's
|
|
|
|
// no need for a mutex here because synchronization happens with `join()` (the
|
|
|
|
// parent thread never reads this packet until the child has exited).
|
|
|
|
//
|
|
|
|
// This packet itself is then stored into a `JoinInner` which in turns is placed
|
|
|
|
// in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
|
|
|
|
// manually worry about impls like Send and Sync. The type `T` should
|
|
|
|
// already always be Send (otherwise the thread could not have been created) and
|
|
|
|
// this type is inherently Sync because no methods take &self. Regardless,
|
|
|
|
// however, we add inheriting impls for Send/Sync to this type to ensure it's
|
|
|
|
// Send/Sync and that future modifications will still appropriately classify it.
|
2014-12-22 16:15:51 +00:00
|
|
|
struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
|
|
|
|
|
2015-04-15 05:13:57 +00:00
|
|
|
unsafe impl<T: Send> Send for Packet<T> {}
|
|
|
|
unsafe impl<T: Sync> Sync for Packet<T> {}
|
2014-12-22 16:15:51 +00:00
|
|
|
|
2015-08-13 17:12:38 +00:00
|
|
|
/// Inner representation for JoinHandle
|
2015-02-17 09:08:53 +00:00
|
|
|
struct JoinInner<T> {
|
2015-04-15 05:13:57 +00:00
|
|
|
native: Option<imp::Thread>,
|
2014-11-25 16:52:10 +00:00
|
|
|
thread: Thread,
|
2014-12-22 16:15:51 +00:00
|
|
|
packet: Packet<T>,
|
2015-02-17 09:08:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> JoinInner<T> {
|
|
|
|
fn join(&mut self) -> Result<T> {
|
2015-04-15 05:13:57 +00:00
|
|
|
self.native.take().unwrap().join();
|
2019-12-22 22:42:04 +00:00
|
|
|
unsafe { (*self.packet.0.get()).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
|
|
|
|
/// means that there is no longer any handle to thread and no way to `join`
|
|
|
|
/// 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();
|
|
|
|
/// ```
|
|
|
|
///
|
2017-05-13 19:19:13 +00:00
|
|
|
/// Child being detached and outliving its parent:
|
|
|
|
///
|
|
|
|
/// ```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")]
|
2015-04-13 21:48:17 +00:00
|
|
|
pub struct JoinHandle<T>(JoinInner<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")]
|
|
|
|
pub fn thread(&self) -> &Thread {
|
|
|
|
&self.0.thread
|
|
|
|
}
|
|
|
|
|
2018-08-28 08:49:45 +00:00
|
|
|
/// Waits for the associated thread to finish.
|
|
|
|
///
|
|
|
|
/// In terms of [atomic memory orderings], the completion of the associated
|
|
|
|
/// thread synchronizes with this function returning. In other words, all
|
|
|
|
/// operations performed by that thread are ordered before all
|
2018-08-15 13:22:54 +00:00
|
|
|
/// operations that happen after `join` returns.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
2016-12-23 10:25:11 +00:00
|
|
|
/// If the child 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")]
|
2015-04-13 21:48:17 +00:00
|
|
|
pub fn join(mut self) -> Result<T> {
|
2015-02-17 09:08:53 +00:00
|
|
|
self.0.join()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-10-29 20:54:09 +00:00
|
|
|
impl<T> AsInner<imp::Thread> for JoinHandle<T> {
|
2019-12-22 22:42:04 +00:00
|
|
|
fn as_inner(&self) -> &imp::Thread {
|
|
|
|
self.0.native.as_ref().unwrap()
|
|
|
|
}
|
2015-10-29 20:54:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
|
2019-12-22 22:42:04 +00:00
|
|
|
fn into_inner(self) -> imp::Thread {
|
|
|
|
self.0.native.unwrap()
|
|
|
|
}
|
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 {
|
2016-11-25 18:21:49 +00:00
|
|
|
f.pad("JoinHandle { .. }")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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>();
|
|
|
|
}
|