2014-11-25 16:52:10 +00:00
|
|
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
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
|
|
|
|
//! owned resources. Thread panic is unrecoverable from within
|
|
|
|
//! the panicking thread (i.e. there is no 'try/catch' in Rust), but
|
2015-02-22 18:43:45 +00:00
|
|
|
//! the panic may optionally be detected from a different thread. If
|
|
|
|
//! the main thread panics, the application will exit with a non-zero
|
2014-11-25 16:52:10 +00:00
|
|
|
//! exit code.
|
|
|
|
//!
|
|
|
|
//! 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:
|
|
|
|
//!
|
2016-12-17 17:09:05 +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.
|
|
|
|
//!
|
2016-12-17 17:09:05 +00:00
|
|
|
//! [channels]: ../../std/sync/mpsc/index.html
|
|
|
|
//! [`Arc`]: ../../std/sync/struct.Arc.html
|
|
|
|
//! [`spawn`]: ../../std/thread/fn.spawn.html
|
|
|
|
//! [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
|
2017-04-06 11:57:40 +00:00
|
|
|
//! [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
|
2016-12-17 17:09:05 +00:00
|
|
|
//! [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
|
|
|
|
//! [`Result`]: ../../std/result/enum.Result.html
|
|
|
|
//! [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
|
|
|
|
//! [`Err`]: ../../std/result/enum.Result.html#variant.Err
|
|
|
|
//! [`panic!`]: ../../std/macro.panic.html
|
|
|
|
//! [`Builder`]: ../../std/thread/struct.Builder.html
|
2017-04-02 10:03:54 +00:00
|
|
|
//! [`thread::current`]: ../../std/thread/fn.current.html
|
2017-05-04 12:04:03 +00:00
|
|
|
//! [`thread::Result`]: ../../std/thread/type.Result.html
|
2016-12-17 17:09:05 +00:00
|
|
|
//! [`Thread`]: ../../std/thread/struct.Thread.html
|
2017-03-12 18:04:52 +00:00
|
|
|
//! [`park`]: ../../std/thread/fn.park.html
|
|
|
|
//! [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
|
|
|
|
//! [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
|
2016-09-04 14:16:25 +00:00
|
|
|
//! [`Cell`]: ../cell/struct.Cell.html
|
|
|
|
//! [`RefCell`]: ../cell/struct.RefCell.html
|
2016-09-16 15:50:34 +00:00
|
|
|
//! [`thread_local!`]: ../macro.thread_local.html
|
2016-09-04 14:16:25 +00:00
|
|
|
//! [`with`]: struct.LocalKey.html#method.with
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#![stable(feature = "rust1", since = "1.0.0")]
|
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
|
|
|
use any::Any;
|
2014-12-22 16:15:51 +00:00
|
|
|
use cell::UnsafeCell;
|
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
|
|
|
use ffi::{CStr, CString};
|
2015-02-17 09:08:53 +00:00
|
|
|
use fmt;
|
|
|
|
use io;
|
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
|
|
|
use panic;
|
|
|
|
use panicking;
|
2016-03-25 04:46:45 +00:00
|
|
|
use str;
|
2015-02-17 23:24:34 +00:00
|
|
|
use sync::{Mutex, Condvar, Arc};
|
2015-03-17 20:33:26 +00:00
|
|
|
use sys::thread as imp;
|
2016-10-05 23:11:28 +00:00
|
|
|
use sys_common::mutex;
|
2015-07-27 20:41:35 +00:00
|
|
|
use sys_common::thread_info;
|
2015-09-08 22:53:46 +00:00
|
|
|
use sys_common::util;
|
2015-10-29 20:54:09 +00:00
|
|
|
use sys_common::{AsInner, IntoInner};
|
2015-01-30 21:44:13 +00:00
|
|
|
use 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;
|
|
|
|
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
pub use self::local::{LocalKey, LocalKeyState};
|
|
|
|
|
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.
|
|
|
|
|
2015-11-16 16:54:28 +00:00
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "0")]
|
2015-12-11 20:42:29 +00:00
|
|
|
#[cfg(target_thread_local)]
|
2016-09-30 20:13:58 +00:00
|
|
|
#[doc(hidden)] pub use sys::fast_thread_local::Key as __FastLocalKeyInner;
|
2015-12-11 20:42:29 +00:00
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "0")]
|
|
|
|
#[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
|
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:
|
|
|
|
///
|
|
|
|
/// - [`name`]: allows to give a name to the thread which is currently
|
|
|
|
/// only used in `panic` messages.
|
|
|
|
/// - [`stack_size`]: specifies the desired stack size. Note that this can
|
|
|
|
/// be overriden by the OS.
|
|
|
|
///
|
|
|
|
/// If the [`stack_size`] field is not specified, the stack size
|
|
|
|
/// will be the `RUST_MIN_STACK` environment variable. If it is
|
|
|
|
/// not specified either, a sensible default will be set.
|
|
|
|
///
|
|
|
|
/// If the [`name`] field is not specified, the thread will not be named.
|
|
|
|
///
|
|
|
|
/// 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
|
|
|
|
/// panick 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
|
|
|
///
|
|
|
|
/// [`thread::spawn`]: ../../std/thread/fn.spawn.html
|
|
|
|
/// [`stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
|
|
|
|
/// [`name`]: ../../std/thread/struct.Builder.html#method.name
|
|
|
|
/// [`spawn`]: ../../std/thread/struct.Builder.html#method.spawn
|
|
|
|
/// [`io::Result`]: ../../std/io/type.Result.html
|
|
|
|
/// [`unwrap`]: ../../std/result/enum.Result.html#method.unwrap
|
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())
|
|
|
|
/// .stack_size(10);
|
|
|
|
///
|
|
|
|
/// 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 {
|
|
|
|
Builder {
|
2014-11-25 16:52:10 +00:00
|
|
|
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
|
|
|
///
|
|
|
|
/// # 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();
|
|
|
|
/// ```
|
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
|
|
|
|
/// the platform specifies minimal 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
|
|
|
/// ```
|
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
|
|
|
///
|
|
|
|
/// [`spawn`]: ../../std/thread/fn.spawn.html
|
|
|
|
/// [`io::Result`]: ../../std/io/type.Result.html
|
2017-05-14 17:35:36 +00:00
|
|
|
/// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
|
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
|
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
|
|
|
|
2015-09-08 22:53:46 +00:00
|
|
|
let stack_size = stack_size.unwrap_or(util::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();
|
|
|
|
|
2015-09-25 23:52:46 +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
|
|
|
}
|
2015-10-19 00:01:55 +00:00
|
|
|
unsafe {
|
|
|
|
thread_info::set(imp::guard::current(), their_thread);
|
2017-05-21 19:38:07 +00:00
|
|
|
#[cfg(feature = "backtrace")]
|
2017-03-04 15:27:52 +00:00
|
|
|
let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
|
|
|
|
::sys_common::backtrace::__rust_begin_short_backtrace(f)
|
|
|
|
}));
|
2017-05-21 19:38:07 +00:00
|
|
|
#[cfg(not(feature = "backtrace"))]
|
|
|
|
let try_result = panic::catch_unwind(panic::AssertUnwindSafe(f));
|
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
|
|
|
*their_packet.get() = Some(try_result);
|
2015-10-19 00:01:55 +00:00
|
|
|
}
|
2014-11-25 16:52:10 +00:00
|
|
|
};
|
|
|
|
|
2015-10-19 00:01:55 +00:00
|
|
|
Ok(JoinHandle(JoinInner {
|
|
|
|
native: unsafe {
|
2016-03-23 03:01:37 +00:00
|
|
|
Some(imp::Thread::new(stack_size, Box::new(main))?)
|
2015-10-19 00:01:55 +00:00
|
|
|
},
|
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
|
|
|
|
/// [`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.
|
|
|
|
/// As a reminder, the [`Send`] marker trait, expresses that it is safe to be
|
|
|
|
/// 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-05-09 17:06:56 +00:00
|
|
|
/// let _ = tx.send("Hello, thread".to_owned());
|
2017-05-09 11:20:04 +00:00
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// let receiver = thread::spawn(move || {
|
|
|
|
/// println!("{}", rx.recv().unwrap());
|
|
|
|
/// });
|
|
|
|
///
|
2017-05-09 17:06:56 +00:00
|
|
|
/// let _ = sender.join();
|
|
|
|
/// let _ = receiver.join();
|
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
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// [`channels`]: ../../std/sync/mpsc/index.html
|
|
|
|
/// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
|
|
|
|
/// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
|
|
|
|
/// [`Err`]: ../../std/result/enum.Result.html#variant.Err
|
|
|
|
/// [`panic`]: ../../std/macro.panic.html
|
|
|
|
/// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
|
2017-05-09 11:27:22 +00:00
|
|
|
/// [`Builder`]: ../../std/thread/struct.Builder.html
|
2017-05-13 18:34:40 +00:00
|
|
|
/// [`Send`]: ../../std/marker/trait.Send.html
|
|
|
|
/// [`Sync`]: ../../std/marker/trait.Sync.html
|
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
|
|
|
|
{
|
2015-02-17 09:08:53 +00:00
|
|
|
Builder::new().spawn(f).unwrap()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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 {
|
2015-04-15 19:27:05 +00:00
|
|
|
thread_info::current_thread().expect("use of std::thread::current() is not \
|
|
|
|
possible after the thread's local \
|
|
|
|
data has been destroyed")
|
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.
|
|
|
|
///
|
|
|
|
/// However programmers will usualy prefer to use, [`channel`]s, [`Condvar`]s,
|
|
|
|
/// [`Mutex`]es or [`join`] for their synchronisation routines, as they avoid
|
|
|
|
/// thinking about thread schedulling.
|
|
|
|
///
|
|
|
|
/// 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
|
|
|
///
|
|
|
|
/// [`channel`]: ../../std/sync/mpsc/index.html
|
|
|
|
/// [`spawn`]: ../../std/thread/fn.spawn.html
|
|
|
|
/// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
|
|
|
|
/// [`Mutex`]: ../../std/sync/struct.Mutex.html
|
|
|
|
/// [`Condvar`]: ../../std/sync/struct.Condvar.html
|
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
|
|
|
|
/// message to other threads warning that a thread has panicked (e.g. for
|
|
|
|
/// 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!()
|
|
|
|
/// }
|
|
|
|
/// ```
|
2017-05-07 14:49:18 +00:00
|
|
|
///
|
|
|
|
/// [Mutex]: ../../std/sync/struct.Mutex.html
|
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
|
|
|
}
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Puts the current thread to sleep for 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
|
2017-01-01 19:53:18 +00:00
|
|
|
/// specifics or platform-dependent functionality.
|
|
|
|
///
|
|
|
|
/// # Platform behavior
|
|
|
|
///
|
|
|
|
/// On Unix platforms this function will not return early due to a
|
|
|
|
/// signal being received or a spurious wakeup.
|
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))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Puts the current thread to sleep for the specified amount of time.
|
|
|
|
///
|
|
|
|
/// The thread may sleep longer than the duration specified due to scheduling
|
|
|
|
/// specifics or platform-dependent functionality.
|
|
|
|
///
|
|
|
|
/// # Platform behavior
|
|
|
|
///
|
|
|
|
/// On Unix platforms this function will not return early due to a
|
|
|
|
/// signal being received or a spurious wakeup. 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
|
|
|
|
/// if it wasn't already.
|
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
|
|
|
///
|
|
|
|
/// 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
|
2017-05-07 16:55:20 +00:00
|
|
|
/// find it, and then `park`ing. When some desired condition is met, another
|
|
|
|
/// 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;
|
2017-05-07 19:43:46 +00:00
|
|
|
/// use std::time::Duration;
|
2017-05-07 16:55:20 +00:00
|
|
|
///
|
|
|
|
/// let parked_thread = thread::Builder::new()
|
|
|
|
/// .spawn(|| {
|
|
|
|
/// println!("Parking thread");
|
|
|
|
/// thread::park();
|
|
|
|
/// println!("Thread unparked");
|
|
|
|
/// })
|
|
|
|
/// .unwrap();
|
|
|
|
///
|
|
|
|
/// // 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();
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// [`Thread`]: ../../std/thread/struct.Thread.html
|
|
|
|
/// [`park`]: ../../std/thread/fn.park.html
|
|
|
|
/// [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
|
|
|
|
/// [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
|
2015-02-17 09:08:53 +00:00
|
|
|
//
|
|
|
|
// The implementation currently uses the trivial strategy of a Mutex+Condvar
|
|
|
|
// with wakeup flag, which does not actually allow spurious wakeups. In the
|
|
|
|
// future, this will be implemented in a more efficient way, perhaps along the lines of
|
|
|
|
// http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
|
|
|
|
// or futuxes, and in either case may allow spurious wakeups.
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
pub fn park() {
|
2015-02-17 23:10:25 +00:00
|
|
|
let thread = current();
|
2015-02-17 09:08:53 +00:00
|
|
|
let mut guard = thread.inner.lock.lock().unwrap();
|
|
|
|
while !*guard {
|
|
|
|
guard = thread.inner.cvar.wait(guard).unwrap();
|
|
|
|
}
|
|
|
|
*guard = false;
|
|
|
|
}
|
|
|
|
|
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.
|
2016-08-03 11:34:49 +00:00
|
|
|
///
|
2017-05-09 17:02:43 +00:00
|
|
|
/// [`park_timeout`]: fn.park_timeout.html
|
|
|
|
/// [`park`]: ../../std/thread/fn.park.html
|
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-05-07 16:55:20 +00:00
|
|
|
/// See the [park dococumentation][park] for more details.
|
2015-04-28 18:40:04 +00:00
|
|
|
///
|
|
|
|
/// # Platform behavior
|
|
|
|
///
|
|
|
|
/// 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
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// 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();
|
|
|
|
/// park_timeout(timeout);
|
|
|
|
///
|
|
|
|
/// while beginning_park.elapsed() < timeout {
|
|
|
|
/// println!("restarting park_timeout after {:?}", beginning_park.elapsed());
|
|
|
|
/// let timeout = timeout - beginning_park.elapsed();
|
|
|
|
/// park_timeout(timeout);
|
|
|
|
/// }
|
|
|
|
/// ```
|
2017-05-07 11:47:39 +00:00
|
|
|
///
|
|
|
|
/// [park]: fn.park.html
|
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) {
|
2015-02-17 23:10:25 +00:00
|
|
|
let thread = current();
|
2015-02-17 09:08:53 +00:00
|
|
|
let mut guard = thread.inner.lock.lock().unwrap();
|
|
|
|
if !*guard {
|
2015-04-28 18:40:04 +00:00
|
|
|
let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
|
2015-02-17 09:08:53 +00:00
|
|
|
guard = g;
|
|
|
|
}
|
|
|
|
*guard = false;
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
/// system-designated identifier.
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(thread_id)]
|
|
|
|
///
|
|
|
|
/// 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
|
|
|
/// ```
|
2016-09-08 04:48:07 +00:00
|
|
|
#[unstable(feature = "thread_id", issue = "21507")]
|
2017-04-04 15:44:57 +00:00
|
|
|
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
|
2016-10-05 16:34:25 +00:00
|
|
|
pub struct ThreadId(u64);
|
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 {
|
2016-10-05 23:11:28 +00:00
|
|
|
static GUARD: mutex::Mutex = mutex::Mutex::new();
|
2016-10-05 16:34:25 +00:00
|
|
|
static mut COUNTER: u64 = 0;
|
|
|
|
|
2016-10-05 23:11:28 +00:00
|
|
|
unsafe {
|
|
|
|
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.
|
|
|
|
if COUNTER == ::u64::MAX {
|
2016-10-07 22:45:04 +00:00
|
|
|
GUARD.unlock();
|
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;
|
|
|
|
|
2016-10-05 23:11:28 +00:00
|
|
|
GUARD.unlock();
|
2016-10-05 16:34:25 +00:00
|
|
|
|
2016-10-05 23:11:28 +00:00
|
|
|
ThreadId(id)
|
|
|
|
}
|
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,
|
2014-11-25 16:52:10 +00:00
|
|
|
lock: Mutex<bool>, // true when there is a buffered unpark
|
|
|
|
cvar: Condvar,
|
|
|
|
}
|
|
|
|
|
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
|
|
|
///
|
2017-05-07 17:26:32 +00:00
|
|
|
/// * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`]
|
|
|
|
/// 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.
|
|
|
|
///
|
|
|
|
/// There is usualy no need to create a `Thread` struct yourself, one
|
|
|
|
/// 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
|
|
|
///
|
2017-04-26 16:54:17 +00:00
|
|
|
/// [`Builder`]: ../../std/thread/struct.Builder.html
|
|
|
|
/// [`spawn`]: ../../std/thread/fn.spawn.html
|
|
|
|
|
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-03-14 01:42:23 +00:00
|
|
|
pub(crate) fn new(name: Option<String>) -> Thread {
|
2016-06-24 12:19:22 +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 {
|
|
|
|
inner: Arc::new(Inner {
|
2016-03-25 04:46:45 +00:00
|
|
|
name: cname,
|
2016-10-05 16:34:25 +00:00
|
|
|
id: ThreadId::new(),
|
2014-11-25 16:52:10 +00:00
|
|
|
lock: Mutex::new(false),
|
|
|
|
cvar: Condvar::new(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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
|
|
|
/// ```
|
2017-05-07 11:54:06 +00:00
|
|
|
///
|
|
|
|
/// [park]: fn.park.html
|
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) {
|
2014-12-09 04:20:03 +00:00
|
|
|
let mut guard = self.inner.lock.lock().unwrap();
|
2014-11-25 16:52:10 +00:00
|
|
|
if !*guard {
|
|
|
|
*guard = true;
|
|
|
|
self.inner.cvar.notify_one();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-05 16:34:25 +00:00
|
|
|
/// Gets the thread's unique identifier.
|
2016-12-22 15:50:34 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(thread_id)]
|
|
|
|
///
|
|
|
|
/// 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
|
|
|
/// ```
|
2016-10-05 16:34:25 +00:00
|
|
|
#[unstable(feature = "thread_id", issue = "21507")]
|
|
|
|
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
|
|
|
///
|
|
|
|
/// # 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();
|
|
|
|
/// ```
|
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> {
|
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> {
|
2015-02-02 02:53:25 +00:00
|
|
|
self.inner.name.as_ref().map(|s| &**s)
|
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 {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
fmt::Debug::fmt(&self.name(), f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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.
|
|
|
|
///
|
|
|
|
/// 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"),
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// [`Result`]: ../../std/result/enum.Result.html
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-13 11:58:37 +00:00
|
|
|
pub type Result<T> = ::result::Result<T, Box<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();
|
2015-02-17 09:08:53 +00:00
|
|
|
unsafe {
|
|
|
|
(*self.packet.0.get()).take().unwrap()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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 ♫");
|
|
|
|
/// });
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// let _ = original_thread.join();
|
|
|
|
/// 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));
|
|
|
|
/// ```
|
|
|
|
///
|
2016-12-23 10:25:11 +00:00
|
|
|
/// [`Clone`]: ../../std/clone/trait.Clone.html
|
2016-06-23 22:16:37 +00:00
|
|
|
/// [`thread::spawn`]: fn.spawn.html
|
|
|
|
/// [`thread::Builder::spawn`]: struct.Builder.html#method.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
|
|
|
|
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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(thread_id)]
|
|
|
|
///
|
|
|
|
/// 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
|
|
|
|
}
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Waits for the associated thread to finish.
|
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
|
|
|
|
/// to [`panic`].
|
|
|
|
///
|
|
|
|
/// [`Err`]: ../../std/result/enum.Result.html#variant.Err
|
2017-01-27 18:08:51 +00:00
|
|
|
/// [`panic`]: ../../std/macro.panic.html
|
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> {
|
|
|
|
fn as_inner(&self) -> &imp::Thread { self.0.native.as_ref().unwrap() }
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
|
|
|
|
fn into_inner(self) -> imp::Thread { self.0.native.unwrap() }
|
|
|
|
}
|
|
|
|
|
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> {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
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>();
|
|
|
|
}
|
|
|
|
|
2015-03-20 07:46:13 +00:00
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Tests
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2016-09-22 20:04:48 +00:00
|
|
|
#[cfg(all(test, not(target_os = "emscripten")))]
|
2015-04-24 15:30:41 +00:00
|
|
|
mod tests {
|
2015-01-01 06:13:08 +00:00
|
|
|
use any::Any;
|
2014-12-23 19:53:35 +00:00
|
|
|
use sync::mpsc::{channel, Sender};
|
2014-11-25 16:52:10 +00:00
|
|
|
use result;
|
2015-02-19 17:57:25 +00:00
|
|
|
use super::{Builder};
|
2015-02-18 03:00:20 +00:00
|
|
|
use thread;
|
2015-01-30 21:44:13 +00:00
|
|
|
use time::Duration;
|
2015-04-01 19:20:57 +00:00
|
|
|
use u32;
|
2014-11-25 16:52:10 +00:00
|
|
|
|
|
|
|
// !!! These tests are dangerous. If something is buggy, they will hang, !!!
|
|
|
|
// !!! instead of exiting cleanly. This might wedge the buildbots. !!!
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_unnamed_thread() {
|
2015-02-17 23:10:25 +00:00
|
|
|
thread::spawn(move|| {
|
|
|
|
assert!(thread::current().name().is_none());
|
2015-01-20 23:45:07 +00:00
|
|
|
}).join().ok().unwrap();
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_named_thread() {
|
2015-08-12 00:27:05 +00:00
|
|
|
Builder::new().name("ada lovelace".to_string()).spawn(move|| {
|
2015-02-17 23:10:25 +00:00
|
|
|
assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
|
2015-08-12 00:27:05 +00:00
|
|
|
}).unwrap().join().unwrap();
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
2016-03-25 04:46:45 +00:00
|
|
|
#[test]
|
|
|
|
#[should_panic]
|
|
|
|
fn test_invalid_named_thread() {
|
|
|
|
let _ = Builder::new().name("ada l\0velace".to_string()).spawn(|| {});
|
|
|
|
}
|
|
|
|
|
2014-11-25 16:52:10 +00:00
|
|
|
#[test]
|
|
|
|
fn test_run_basic() {
|
|
|
|
let (tx, rx) = channel();
|
2015-02-17 23:10:25 +00:00
|
|
|
thread::spawn(move|| {
|
2014-12-23 19:53:35 +00:00
|
|
|
tx.send(()).unwrap();
|
2015-01-06 05:59:45 +00:00
|
|
|
});
|
2014-12-23 19:53:35 +00:00
|
|
|
rx.recv().unwrap();
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_join_panic() {
|
2015-02-17 23:10:25 +00:00
|
|
|
match thread::spawn(move|| {
|
2014-11-25 16:52:10 +00:00
|
|
|
panic!()
|
|
|
|
}).join() {
|
|
|
|
result::Result::Err(_) => (),
|
|
|
|
result::Result::Ok(()) => panic!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_spawn_sched() {
|
|
|
|
let (tx, rx) = channel();
|
|
|
|
|
2015-02-18 23:23:55 +00:00
|
|
|
fn f(i: i32, tx: Sender<()>) {
|
2014-11-25 16:52:10 +00:00
|
|
|
let tx = tx.clone();
|
2015-02-17 23:10:25 +00:00
|
|
|
thread::spawn(move|| {
|
2014-11-25 16:52:10 +00:00
|
|
|
if i == 0 {
|
2014-12-23 19:53:35 +00:00
|
|
|
tx.send(()).unwrap();
|
2014-11-25 16:52:10 +00:00
|
|
|
} else {
|
|
|
|
f(i - 1, tx);
|
|
|
|
}
|
2015-01-06 05:59:45 +00:00
|
|
|
});
|
2014-11-25 16:52:10 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
f(10, tx);
|
2014-12-23 19:53:35 +00:00
|
|
|
rx.recv().unwrap();
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_spawn_sched_childs_on_default_sched() {
|
|
|
|
let (tx, rx) = channel();
|
|
|
|
|
2015-02-17 23:10:25 +00:00
|
|
|
thread::spawn(move|| {
|
|
|
|
thread::spawn(move|| {
|
2014-12-23 19:53:35 +00:00
|
|
|
tx.send(()).unwrap();
|
2015-01-06 05:59:45 +00:00
|
|
|
});
|
|
|
|
});
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2014-12-23 19:53:35 +00:00
|
|
|
rx.recv().unwrap();
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
2015-08-12 00:27:05 +00:00
|
|
|
fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Box<Fn() + Send>) {
|
2015-03-02 22:56:13 +00:00
|
|
|
let (tx, rx) = channel();
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2015-02-17 20:41:32 +00:00
|
|
|
let x: Box<_> = box 1;
|
2015-03-02 22:56:13 +00:00
|
|
|
let x_in_parent = (&*x) as *const i32 as usize;
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2015-04-01 15:12:30 +00:00
|
|
|
spawnfn(Box::new(move|| {
|
2015-03-02 22:56:13 +00:00
|
|
|
let x_in_child = (&*x) as *const i32 as usize;
|
2014-12-23 19:53:35 +00:00
|
|
|
tx.send(x_in_child).unwrap();
|
2014-12-14 08:05:32 +00:00
|
|
|
}));
|
2014-11-25 16:52:10 +00:00
|
|
|
|
2014-12-23 19:53:35 +00:00
|
|
|
let x_in_child = rx.recv().unwrap();
|
2014-11-25 16:52:10 +00:00
|
|
|
assert_eq!(x_in_parent, x_in_child);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_avoid_copying_the_body_spawn() {
|
2014-12-14 08:05:32 +00:00
|
|
|
avoid_copying_the_body(|v| {
|
2015-04-01 15:12:30 +00:00
|
|
|
thread::spawn(move || v());
|
2014-12-14 08:05:32 +00:00
|
|
|
});
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_avoid_copying_the_body_thread_spawn() {
|
|
|
|
avoid_copying_the_body(|f| {
|
2015-02-17 23:10:25 +00:00
|
|
|
thread::spawn(move|| {
|
2015-04-01 15:12:30 +00:00
|
|
|
f();
|
2015-01-06 05:59:45 +00:00
|
|
|
});
|
2014-11-25 16:52:10 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_avoid_copying_the_body_join() {
|
|
|
|
avoid_copying_the_body(|f| {
|
2015-02-17 23:10:25 +00:00
|
|
|
let _ = thread::spawn(move|| {
|
2015-04-01 15:12:30 +00:00
|
|
|
f()
|
2014-11-25 16:52:10 +00:00
|
|
|
}).join();
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_child_doesnt_ref_parent() {
|
2015-05-08 15:12:29 +00:00
|
|
|
// If the child refcounts the parent thread, this will stack overflow when
|
|
|
|
// climbing the thread tree to dereference each ancestor. (See #1789)
|
2014-11-25 16:52:10 +00:00
|
|
|
// (well, it would if the constant were 8000+ - I lowered it to be more
|
|
|
|
// valgrind-friendly. try this at home, instead..!)
|
2015-03-02 22:56:13 +00:00
|
|
|
const GENERATIONS: u32 = 16;
|
2015-08-12 00:27:05 +00:00
|
|
|
fn child_no(x: u32) -> Box<Fn() + Send> {
|
2015-04-01 15:12:30 +00:00
|
|
|
return Box::new(move|| {
|
2014-11-25 16:52:10 +00:00
|
|
|
if x < GENERATIONS {
|
2015-04-01 15:12:30 +00:00
|
|
|
thread::spawn(move|| child_no(x+1)());
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
2014-12-14 08:05:32 +00:00
|
|
|
});
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
2015-04-01 15:12:30 +00:00
|
|
|
thread::spawn(|| child_no(0)());
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_simple_newsched_spawn() {
|
2015-02-17 23:10:25 +00:00
|
|
|
thread::spawn(move || {});
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_try_panic_message_static_str() {
|
2015-02-17 23:10:25 +00:00
|
|
|
match thread::spawn(move|| {
|
2014-11-25 16:52:10 +00:00
|
|
|
panic!("static string");
|
|
|
|
}).join() {
|
|
|
|
Err(e) => {
|
|
|
|
type T = &'static str;
|
|
|
|
assert!(e.is::<T>());
|
2015-03-20 07:19:13 +00:00
|
|
|
assert_eq!(*e.downcast::<T>().unwrap(), "static string");
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
Ok(()) => panic!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_try_panic_message_owned_str() {
|
2015-02-17 23:10:25 +00:00
|
|
|
match thread::spawn(move|| {
|
2014-11-25 16:52:10 +00:00
|
|
|
panic!("owned string".to_string());
|
|
|
|
}).join() {
|
|
|
|
Err(e) => {
|
|
|
|
type T = String;
|
|
|
|
assert!(e.is::<T>());
|
2015-03-20 07:19:13 +00:00
|
|
|
assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
Ok(()) => panic!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_try_panic_message_any() {
|
2015-02-17 23:10:25 +00:00
|
|
|
match thread::spawn(move|| {
|
2014-11-25 16:52:10 +00:00
|
|
|
panic!(box 413u16 as Box<Any + Send>);
|
|
|
|
}).join() {
|
|
|
|
Err(e) => {
|
|
|
|
type T = Box<Any + Send>;
|
|
|
|
assert!(e.is::<T>());
|
2015-03-20 07:19:13 +00:00
|
|
|
let any = e.downcast::<T>().unwrap();
|
2014-11-25 16:52:10 +00:00
|
|
|
assert!(any.is::<u16>());
|
2015-03-20 07:19:13 +00:00
|
|
|
assert_eq!(*any.downcast::<u16>().unwrap(), 413);
|
2014-11-25 16:52:10 +00:00
|
|
|
}
|
|
|
|
Ok(()) => panic!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_try_panic_message_unit_struct() {
|
|
|
|
struct Juju;
|
|
|
|
|
2015-02-17 23:10:25 +00:00
|
|
|
match thread::spawn(move|| {
|
2014-11-25 16:52:10 +00:00
|
|
|
panic!(Juju)
|
|
|
|
}).join() {
|
|
|
|
Err(ref e) if e.is::<Juju>() => {}
|
|
|
|
Err(_) | Ok(()) => panic!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-30 21:44:13 +00:00
|
|
|
#[test]
|
|
|
|
fn test_park_timeout_unpark_before() {
|
|
|
|
for _ in 0..10 {
|
2015-02-17 23:10:25 +00:00
|
|
|
thread::current().unpark();
|
2015-12-18 12:29:49 +00:00
|
|
|
thread::park_timeout(Duration::from_millis(u32::MAX as u64));
|
2015-01-30 21:44:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_park_timeout_unpark_not_called() {
|
|
|
|
for _ in 0..10 {
|
2015-12-18 12:29:49 +00:00
|
|
|
thread::park_timeout(Duration::from_millis(10));
|
2015-01-30 21:44:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_park_timeout_unpark_called_other_thread() {
|
|
|
|
for _ in 0..10 {
|
2015-02-17 23:10:25 +00:00
|
|
|
let th = thread::current();
|
2015-01-30 21:44:13 +00:00
|
|
|
|
2015-02-17 23:10:25 +00:00
|
|
|
let _guard = thread::spawn(move || {
|
2015-12-18 12:29:49 +00:00
|
|
|
super::sleep(Duration::from_millis(50));
|
2015-01-30 21:44:13 +00:00
|
|
|
th.unpark();
|
|
|
|
});
|
|
|
|
|
2015-12-18 12:29:49 +00:00
|
|
|
thread::park_timeout(Duration::from_millis(u32::MAX as u64));
|
2015-01-30 21:44:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-13 03:36:31 +00:00
|
|
|
#[test]
|
2015-04-01 19:20:57 +00:00
|
|
|
fn sleep_ms_smoke() {
|
2015-12-18 12:29:49 +00:00
|
|
|
thread::sleep(Duration::from_millis(2));
|
2015-03-13 03:36:31 +00:00
|
|
|
}
|
|
|
|
|
2016-09-08 04:48:07 +00:00
|
|
|
#[test]
|
|
|
|
fn test_thread_id_equal() {
|
2016-10-05 16:34:25 +00:00
|
|
|
assert!(thread::current().id() == thread::current().id());
|
2016-09-08 04:48:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_thread_id_not_equal() {
|
2016-10-05 16:34:25 +00:00
|
|
|
let spawned_id = thread::spawn(|| thread::current().id()).join().unwrap();
|
|
|
|
assert!(thread::current().id() != spawned_id);
|
2016-09-08 04:48:07 +00:00
|
|
|
}
|
|
|
|
|
2015-05-08 15:12:29 +00:00
|
|
|
// NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
|
2014-11-25 16:52:10 +00:00
|
|
|
// to the test harness apparently interfering with stderr configuration.
|
|
|
|
}
|