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,
|
|
|
|
//! each with their own stack and local state.
|
|
|
|
//!
|
2014-12-14 08:05:32 +00:00
|
|
|
//! Communication between threads can be done through
|
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
|
|
|
//! [channels](../../std/sync/mpsc/index.html), Rust's message-passing
|
2014-12-14 08:05:32 +00:00
|
|
|
//! types, along with [other forms of thread
|
|
|
|
//! 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
|
2014-11-25 16:52:10 +00:00
|
|
|
//! atomically-reference-counted container,
|
|
|
|
//! [`Arc`](../../std/sync/struct.Arc.html).
|
|
|
|
//!
|
|
|
|
//! 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
|
|
|
//!
|
|
|
|
//! ## The `Thread` type
|
|
|
|
//!
|
2015-02-22 18:43:45 +00:00
|
|
|
//! Threads are represented via the `Thread` type, which you can
|
2014-11-25 16:52:10 +00:00
|
|
|
//! get in one of two ways:
|
|
|
|
//!
|
2015-02-22 18:43:45 +00:00
|
|
|
//! * By spawning a new thread, e.g. using the `thread::spawn` function.
|
2015-02-17 23:10:25 +00:00
|
|
|
//! * By requesting the current thread, using the `thread::current` function.
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
|
|
|
//! Threads can be named, and provide some built-in support for low-level
|
2015-02-22 18:43:45 +00:00
|
|
|
//! synchronization (described below).
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
2015-02-17 23:10:25 +00:00
|
|
|
//! The `thread::current()` function is available even for threads not spawned
|
2014-11-25 16:52:10 +00:00
|
|
|
//! by the APIs of this module.
|
|
|
|
//!
|
|
|
|
//! ## Spawning a thread
|
|
|
|
//!
|
2015-02-17 23:10:25 +00:00
|
|
|
//! A new thread can be spawned using the `thread::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
|
|
|
|
//! thread; a call to `spawn` produces a `JoinHandle`, which provides
|
|
|
|
//! a `join` method for waiting:
|
|
|
|
//!
|
|
|
|
//! ```rust
|
|
|
|
//! use std::thread;
|
|
|
|
//!
|
|
|
|
//! let child = thread::spawn(move || {
|
|
|
|
//! // some work here
|
|
|
|
//! });
|
|
|
|
//! // some work here
|
|
|
|
//! let res = child.join();
|
|
|
|
//! ```
|
|
|
|
//!
|
|
|
|
//! The `join` method returns a `Result` containing `Ok` of the final
|
|
|
|
//! value produced by the child thread, or `Err` of the value given to
|
|
|
|
//! a call to `panic!` if the child panicked.
|
|
|
|
//!
|
2014-12-14 08:05:32 +00:00
|
|
|
//! ## Configuring threads
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
2014-12-14 08:05:32 +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
|
|
|
//! ```
|
|
|
|
//!
|
|
|
|
//! ## Blocking support: park and unpark
|
|
|
|
//!
|
|
|
|
//! Every thread is equipped with some basic low-level blocking support, via the
|
|
|
|
//! `park` and `unpark` functions.
|
|
|
|
//!
|
|
|
|
//! Conceptually, each `Thread` handle has an associated token, which is
|
|
|
|
//! initially not present:
|
|
|
|
//!
|
2015-02-17 23:10:25 +00:00
|
|
|
//! * The `thread::park()` function blocks the current thread unless or until
|
2015-02-22 18:43:45 +00:00
|
|
|
//! the token is available for its thread handle, at which point it atomically
|
2014-11-25 16:52:10 +00:00
|
|
|
//! consumes the token. It may also return *spuriously*, without consuming the
|
2015-02-17 23:10:25 +00:00
|
|
|
//! token. `thread::park_timeout()` does the same, but allows specifying a
|
2015-01-30 21:44:13 +00:00
|
|
|
//! maximum time to block the thread for.
|
2014-11-25 16:52:10 +00:00
|
|
|
//!
|
|
|
|
//! * The `unpark()` method on a `Thread` atomically makes the token available
|
|
|
|
//! if it wasn't already.
|
|
|
|
//!
|
|
|
|
//! In other words, each `Thread` acts a bit like a semaphore with initial count
|
|
|
|
//! 0, except that the semaphore is *saturating* (the count cannot go above 1),
|
|
|
|
//! and can return spuriously.
|
|
|
|
//!
|
|
|
|
//! 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
|
|
|
|
//! find it, and then `park`ing. When some desired condition is met, another
|
|
|
|
//! thread calls `unpark` on the handle.
|
|
|
|
//!
|
|
|
|
//! 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-02-22 18:43:45 +00:00
|
|
|
//! * It can be implemented very efficiently on many platforms.
|
2015-03-20 07:46:13 +00:00
|
|
|
//!
|
|
|
|
//! ## Thread-local storage
|
|
|
|
//!
|
|
|
|
//! 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 which each thread in the program will have its own copy of.
|
|
|
|
//! Threads do not share this data, so accesses do not need to be synchronized.
|
|
|
|
//!
|
|
|
|
//! At a high level, this module provides two variants of storage:
|
|
|
|
//!
|
|
|
|
//! * Owned thread-local storage. This is a type of thread local key which
|
|
|
|
//! owns the value that it contains, and will destroy the value when the
|
|
|
|
//! thread exits. This variant is created with the `thread_local!` macro and
|
|
|
|
//! can contain any value which is `'static` (no borrowed pointers).
|
|
|
|
//!
|
|
|
|
//! * Scoped thread-local storage. This type of key is used to store a reference
|
|
|
|
//! to a value into local storage temporarily for the scope of a function
|
|
|
|
//! call. There are no restrictions on what types of values can be placed
|
|
|
|
//! into this key.
|
|
|
|
//!
|
|
|
|
//! Both forms of thread local storage provide an accessor function, `with`,
|
|
|
|
//! which will yield a shared reference to the value to the specified
|
|
|
|
//! closure. Thread-local keys only allow shared access to values as there is no
|
|
|
|
//! way to guarantee uniqueness if a mutable borrow was allowed. Most values
|
|
|
|
//! will want to make use of some form of **interior mutability** through the
|
|
|
|
//! `Cell` or `RefCell` types.
|
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
|
|
|
|
2015-02-17 23:24:34 +00:00
|
|
|
use prelude::v1::*;
|
|
|
|
|
2014-11-25 16:52:10 +00:00
|
|
|
use any::Any;
|
2014-12-22 16:15:51 +00:00
|
|
|
use cell::UnsafeCell;
|
2015-02-17 09:08:53 +00:00
|
|
|
use fmt;
|
|
|
|
use io;
|
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;
|
2015-07-27 20:41:35 +00:00
|
|
|
use sys_common::thread_info;
|
2015-09-08 22:53:46 +00:00
|
|
|
use sys_common::unwind;
|
|
|
|
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;
|
2015-04-13 04:42:59 +00:00
|
|
|
#[macro_use] mod scoped_tls;
|
2015-04-08 00:10:09 +00:00
|
|
|
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
pub use self::local::{LocalKey, LocalKeyState};
|
|
|
|
|
|
|
|
#[unstable(feature = "scoped_tls",
|
2015-08-13 17:12:38 +00:00
|
|
|
reason = "scoped TLS has yet to have wide enough use to fully \
|
|
|
|
consider stabilizing its interface",
|
|
|
|
issue = "27715")]
|
std: Stabilize APIs for the 1.8 release
This commit is the result of the FCPs ending for the 1.8 release cycle for both
the libs and the lang suteams. The full list of changes are:
Stabilized
* `braced_empty_structs`
* `augmented_assignments`
* `str::encode_utf16` - renamed from `utf16_units`
* `str::EncodeUtf16` - renamed from `Utf16Units`
* `Ref::map`
* `RefMut::map`
* `ptr::drop_in_place`
* `time::Instant`
* `time::SystemTime`
* `{Instant,SystemTime}::now`
* `{Instant,SystemTime}::duration_since` - renamed from `duration_from_earlier`
* `{Instant,SystemTime}::elapsed`
* Various `Add`/`Sub` impls for `Time` and `SystemTime`
* `SystemTimeError`
* `SystemTimeError::duration`
* Various impls for `SystemTimeError`
* `UNIX_EPOCH`
* `ops::{Add,Sub,Mul,Div,Rem,BitAnd,BitOr,BitXor,Shl,Shr}Assign`
Deprecated
* Scoped TLS (the `scoped_thread_local!` macro)
* `Ref::filter_map`
* `RefMut::filter_map`
* `RwLockReadGuard::map`
* `RwLockWriteGuard::map`
* `Condvar::wait_timeout_with`
Closes #27714
Closes #27715
Closes #27746
Closes #27748
Closes #27908
Closes #29866
2016-02-25 23:52:29 +00:00
|
|
|
#[allow(deprecated)]
|
2015-04-13 04:42:59 +00:00
|
|
|
pub use self::scoped_tls::ScopedKey;
|
2015-03-20 07:46:13 +00:00
|
|
|
|
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)]
|
|
|
|
#[doc(hidden)] pub use self::local::elf::Key as __ElfLocalKeyInner;
|
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "0")]
|
|
|
|
#[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
|
2015-11-16 16:54:28 +00:00
|
|
|
#[unstable(feature = "libstd_thread_internals", issue = "0")]
|
2015-06-01 20:57:27 +00:00
|
|
|
#[doc(hidden)] pub use self::scoped_tls::__KeyInner as __ScopedKeyInner;
|
2015-03-20 07:46:13 +00:00
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Builder
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2015-01-07 01:53:18 +00:00
|
|
|
/// Thread configuration. Provides detailed control over the properties
|
2014-11-25 16:52:10 +00:00
|
|
|
/// and behavior of new 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 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>,
|
|
|
|
// The size of the stack for the spawned thread
|
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.
|
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.
|
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
|
|
|
|
}
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Sets the size of the stack for the new thread.
|
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
|
|
|
|
}
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Spawns a new thread, and returns a join handle for it.
|
2014-12-14 08:05:32 +00:00
|
|
|
///
|
2015-02-17 09:08:53 +00:00
|
|
|
/// The child thread may outlive the parent (unless the parent thread
|
|
|
|
/// 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.
|
|
|
|
///
|
|
|
|
/// # Errors
|
|
|
|
///
|
|
|
|
/// Unlike the `spawn` free function, this method yields an
|
|
|
|
/// `io::Result` to capture any failure to create the thread at
|
|
|
|
/// the OS level.
|
|
|
|
#[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 || {
|
2015-04-15 05:13:57 +00:00
|
|
|
if let Some(name) = their_thread.name() {
|
|
|
|
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);
|
|
|
|
let mut output = None;
|
|
|
|
let try_result = {
|
|
|
|
let ptr = &mut output;
|
|
|
|
unwind::try(move || *ptr = Some(f()))
|
|
|
|
};
|
|
|
|
*their_packet.get() = Some(try_result.map(|()| {
|
|
|
|
output.unwrap()
|
|
|
|
}));
|
|
|
|
}
|
2014-11-25 16:52:10 +00:00
|
|
|
};
|
|
|
|
|
2015-10-19 00:01:55 +00:00
|
|
|
Ok(JoinHandle(JoinInner {
|
|
|
|
native: unsafe {
|
|
|
|
Some(try!(imp::Thread::new(stack_size, 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
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2015-04-13 14:21:32 +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
|
|
|
|
/// the main thread finishes.) Additionally, the join handle provides a `join`
|
|
|
|
/// method that can be used to join the child thread. If the child thread
|
|
|
|
/// panics, `join` will return an `Err` containing the argument given to
|
|
|
|
/// `panic`.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
2015-04-10 16:42:36 +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.
|
|
|
|
#[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.
|
|
|
|
#[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.
|
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.
|
|
|
|
#[inline]
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
pub fn panicking() -> bool {
|
|
|
|
unwind::panicking()
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
/// specifics or platform-dependent functionality. Note that on unix platforms
|
|
|
|
/// this function will not return early due to a signal being received or a
|
|
|
|
/// spurious wakeup.
|
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.
|
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
|
|
|
///
|
2015-07-07 13:35:56 +00:00
|
|
|
/// Every thread is equipped with some basic low-level blocking support, via
|
|
|
|
/// the `park()` function and the [`unpark()`][unpark] method. These can be
|
|
|
|
/// used as a more CPU-efficient implementation of a spinlock.
|
|
|
|
///
|
|
|
|
/// [unpark]: struct.Thread.html#method.unpark
|
|
|
|
///
|
|
|
|
/// 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
|
|
|
|
/// find it, and then parking (in a loop with a check for the token actually
|
|
|
|
/// being acquired).
|
|
|
|
///
|
|
|
|
/// A call to `park` does not guarantee that the thread will remain parked
|
|
|
|
/// forever, and callers should be prepared for this possibility.
|
|
|
|
///
|
|
|
|
/// See the [module documentation][thread] for more detail.
|
|
|
|
///
|
|
|
|
/// [thread]: index.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;
|
|
|
|
}
|
|
|
|
|
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).
|
|
|
|
///
|
|
|
|
/// The semantics of this function are equivalent to `park()` except that the
|
2015-04-28 18:40:04 +00:00
|
|
|
/// thread will be blocked for roughly no longer than *ms*. This method
|
2015-02-17 09:08:53 +00:00
|
|
|
/// should not be used for precise timing due to anomalies such as
|
|
|
|
/// preemption or platform differences that may not cause the maximum
|
2015-04-28 18:40:04 +00:00
|
|
|
/// amount of time waited to be precisely *ms* long.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
|
|
|
/// See the module doc 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).
|
|
|
|
///
|
|
|
|
/// The semantics of this function are equivalent to `park()` except 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
|
|
|
|
/// preemption or platform differences that may not cause the maximum
|
|
|
|
/// amount of time waited to be precisely *dur* long.
|
|
|
|
///
|
|
|
|
/// See the module doc for more detail.
|
|
|
|
///
|
|
|
|
/// # 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.
|
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;
|
|
|
|
}
|
|
|
|
|
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 {
|
|
|
|
name: Option<String>,
|
|
|
|
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")]
|
2014-11-25 16:52:10 +00:00
|
|
|
/// A handle to a thread.
|
|
|
|
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
|
2014-11-25 16:52:10 +00:00
|
|
|
fn new(name: Option<String>) -> Thread {
|
|
|
|
Thread {
|
|
|
|
inner: Arc::new(Inner {
|
|
|
|
name: name,
|
|
|
|
lock: Mutex::new(false),
|
|
|
|
cvar: Condvar::new(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Atomically makes the handle's token available if it is not already.
|
|
|
|
///
|
|
|
|
/// See the module doc for more detail.
|
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();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Gets the thread's name.
|
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> {
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-11-25 16:52:10 +00:00
|
|
|
// a hack to get around privacy restrictions
|
|
|
|
impl thread_info::NewThread for Thread {
|
|
|
|
fn new(name: Option<String>) -> Thread { Thread::new(name) }
|
|
|
|
}
|
|
|
|
|
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
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
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.
|
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).
|
|
|
|
///
|
2015-08-13 17:12:38 +00:00
|
|
|
/// A `JoinHandle` *detaches* the child thread when it is dropped.
|
2015-02-17 09:08:53 +00:00
|
|
|
///
|
|
|
|
/// Due to platform restrictions, it is not possible to `Clone` this
|
|
|
|
/// handle: the ability to join a child thread is a uniquely-owned
|
|
|
|
/// permission.
|
|
|
|
#[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> {
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Extracts a handle to the underlying thread
|
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
|
|
|
///
|
|
|
|
/// If the child thread panics, `Err` is returned with the parameter given
|
|
|
|
/// to `panic`.
|
|
|
|
#[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() }
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
////////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2014-11-25 16:52:10 +00:00
|
|
|
#[cfg(test)]
|
2015-04-24 15:30:41 +00:00
|
|
|
mod tests {
|
2014-12-22 17:04:23 +00:00
|
|
|
use prelude::v1::*;
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
#[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() {
|
|
|
|
use clone::Clone;
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
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.
|
|
|
|
}
|