Browse Source

Thread fixes + module update

pull/10/head
Fenrir 8 years ago
parent
commit
361c812e6a
  1. 6
      ctr-std/src/panicking.rs
  2. 19
      ctr-std/src/sys/unix/fast_thread_local.rs
  3. 30
      ctr-std/src/sys/unix/thread.rs
  4. 18
      ctr-std/src/sys_common/thread_info.rs
  5. 269
      ctr-std/src/thread/local.rs
  6. 494
      ctr-std/src/thread/mod.rs

6
ctr-std/src/panicking.rs

@ -30,6 +30,12 @@ thread_local! { @@ -30,6 +30,12 @@ thread_local! {
#[lang = "eh_personality"]
pub extern fn eh_personality() {}
/// Determines whether the current thread is unwinding because of panic.
// Which it won't be, since we still don't have stack unwinding.
pub fn panicking() -> bool {
false
}
/// Entry point of panic from the libcore crate.
#[lang = "panic_fmt"]
pub extern fn rust_begin_panic(msg: fmt::Arguments,

19
ctr-std/src/sys/unix/fast_thread_local.rs

@ -12,9 +12,10 @@ @@ -12,9 +12,10 @@
#![unstable(feature = "thread_local_internals", issue = "0")]
use cell::{Cell, UnsafeCell};
use intrinsics;
use mem;
use ptr;
pub struct Key<T> {
inner: UnsafeCell<Option<T>>,
@ -37,7 +38,7 @@ impl<T> Key<T> { @@ -37,7 +38,7 @@ impl<T> Key<T> {
pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
unsafe {
if intrinsics::needs_drop::<T>() && self.dtor_running.get() {
if mem::needs_drop::<T>() && self.dtor_running.get() {
return None
}
self.register_dtor();
@ -46,7 +47,7 @@ impl<T> Key<T> { @@ -46,7 +47,7 @@ impl<T> Key<T> {
}
unsafe fn register_dtor(&self) {
if !intrinsics::needs_drop::<T>() || self.dtor_registered.get() {
if !mem::needs_drop::<T>() || self.dtor_registered.get() {
return
}
@ -56,7 +57,7 @@ impl<T> Key<T> { @@ -56,7 +57,7 @@ impl<T> Key<T> {
}
}
unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
// The fallback implementation uses a vanilla OS-based TLS key to track
// the list of destructors that need to be run for this thread. The key
// then has its own destructor which runs all the other destructors.
@ -96,17 +97,17 @@ pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { @@ -96,17 +97,17 @@ pub unsafe extern fn destroy_value<T>(ptr: *mut u8) {
// `None`.
(*ptr).dtor_running.set(true);
// The OSX implementation of TLS apparently had an odd aspect to it
// The macOS implementation of TLS apparently had an odd aspect to it
// where the pointer we have may be overwritten while this destructor
// is running. Specifically if a TLS destructor re-accesses TLS it may
// trigger a re-initialization of all TLS variables, paving over at
// least some destroyed ones with initial values.
//
// This means that if we drop a TLS value in place on OSX that we could
// This means that if we drop a TLS value in place on macOS that we could
// revert the value to its original state halfway through the
// destructor, which would be bad!
//
// Hence, we use `ptr::read` on OSX (to move to a "safe" location)
// Hence, we use `ptr::read` on macOS (to move to a "safe" location)
// instead of drop_in_place.
if cfg!(target_os = "macos") {
ptr::read((*ptr).inner.get());
@ -114,3 +115,7 @@ pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { @@ -114,3 +115,7 @@ pub unsafe extern fn destroy_value<T>(ptr: *mut u8) {
ptr::drop_in_place((*ptr).inner.get());
}
}
pub fn requires_move_before_drop() -> bool {
false
}

30
ctr-std/src/sys/unix/thread.rs

@ -18,9 +18,9 @@ use ptr; @@ -18,9 +18,9 @@ use ptr;
use sys_common::thread::start_thread;
use time::Duration;
use libctru::{svcSleepThread, svcGetThreadPriority};
use libctru::{threadCreate, threadJoin, threadFree};
use libctru::Thread as ThreadHandle;
use libctru::{svcSleepThread, svcGetThreadPriority,
threadCreate, threadJoin, threadFree, threadDetach,
Thread as ThreadHandle};
pub struct Thread {
handle: ThreadHandle,
@ -36,12 +36,8 @@ impl Thread { @@ -36,12 +36,8 @@ impl Thread {
let p = box p;
let stack_size = cmp::max(stack, 0x10000);
// this retrieves the main thread's priority value. child threads need
// to be spawned with a greater priority (smaller priority value) than
// the main thread
let mut priority = 0;
svcGetThreadPriority(&mut priority, 0xFFFF8000);
priority -= 1;
let handle = threadCreate(Some(thread_func), &*p as *const _ as *mut _,
stack_size, priority, -2, false);
@ -59,11 +55,11 @@ impl Thread { @@ -59,11 +55,11 @@ impl Thread {
}
pub fn yield_now() {
unimplemented!()
unsafe { svcSleepThread(0) }
}
pub fn set_name(_name: &CStr) {
// can't set thread names on the 3DS
// threads aren't named in libctru
}
pub fn sleep(dur: Duration) {
@ -82,12 +78,20 @@ impl Thread { @@ -82,12 +78,20 @@ impl Thread {
}
}
pub fn id(&self) -> usize {
unimplemented!()
pub fn id(&self) -> ThreadHandle {
self.handle
}
pub fn into_id(self) -> usize {
unimplemented!()
pub fn into_id(self) -> ThreadHandle {
let handle = self.handle;
mem::forget(self);
handle
}
}
impl Drop for Thread {
fn drop(&mut self) {
unsafe { threadDetach(self.handle) }
}
}

18
ctr-std/src/sys_common/thread_info.rs

@ -12,7 +12,6 @@ @@ -12,7 +12,6 @@
use cell::RefCell;
use thread::Thread;
use thread::LocalKeyState;
struct ThreadInfo {
stack_guard: Option<usize>,
@ -23,19 +22,15 @@ thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = RefCell::new(N @@ -23,19 +22,15 @@ thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = RefCell::new(N
impl ThreadInfo {
fn with<R, F>(f: F) -> Option<R> where F: FnOnce(&mut ThreadInfo) -> R {
if THREAD_INFO.state() == LocalKeyState::Destroyed {
return None
}
THREAD_INFO.with(move |c| {
THREAD_INFO.try_with(move |c| {
if c.borrow().is_none() {
*c.borrow_mut() = Some(ThreadInfo {
stack_guard: None,
thread: NewThread::new(None),
thread: Thread::new(None),
})
}
Some(f(c.borrow_mut().as_mut().unwrap()))
})
f(c.borrow_mut().as_mut().unwrap())
}).ok()
}
}
@ -54,8 +49,3 @@ pub fn set(stack_guard: Option<usize>, thread: Thread) { @@ -54,8 +49,3 @@ pub fn set(stack_guard: Option<usize>, thread: Thread) {
thread: thread,
}));
}
// a hack to get around privacy restrictions; implemented by `std::thread`
pub trait NewThread {
fn new(name: Option<String>) -> Self;
}

269
ctr-std/src/thread/local.rs

@ -19,17 +19,17 @@ use mem; @@ -19,17 +19,17 @@ use mem;
/// A thread local storage key which owns its contents.
///
/// This key uses the fastest possible implementation available to it for the
/// target platform. It is instantiated with the `thread_local!` macro and the
/// primary method is the `with` method.
/// target platform. It is instantiated with the [`thread_local!`] macro and the
/// primary method is the [`with`] method.
///
/// The `with` method yields a reference to the contained value which cannot be
/// The [`with`] method yields a reference to the contained value which cannot be
/// sent across threads or escape the given closure.
///
/// # Initialization and Destruction
///
/// Initialization is dynamically performed on the first call to `with()`
/// within a thread, and values support destructors which will be run when a
/// thread exits.
/// Initialization is dynamically performed on the first call to [`with`]
/// within a thread, and values that implement [`Drop`] get destructed when a
/// thread exits. Some caveats apply, which are explained below.
///
/// # Examples
///
@ -74,9 +74,13 @@ use mem; @@ -74,9 +74,13 @@ use mem;
/// destroyed, but not all platforms have this guard. Those platforms that do
/// not guard typically have a synthetic limit after which point no more
/// destructors are run.
/// 3. On OSX, initializing TLS during destruction of other TLS slots can
/// 3. On macOS, initializing TLS during destruction of other TLS slots can
/// sometimes cancel *all* destructors for the current thread, whether or not
/// the slots have already had their destructors run or not.
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
/// [`thread_local!`]: ../../std/macro.thread_local.html
/// [`Drop`]: ../../std/ops/trait.Drop.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct LocalKey<T: 'static> {
// This outer `LocalKey<T>` type is what's going to be stored in statics,
@ -106,12 +110,12 @@ impl<T: 'static> fmt::Debug for LocalKey<T> { @@ -106,12 +110,12 @@ impl<T: 'static> fmt::Debug for LocalKey<T> {
}
}
/// Declare a new thread local storage key of type `std::thread::LocalKey`.
/// Declare a new thread local storage key of type [`std::thread::LocalKey`].
///
/// # Syntax
///
/// The macro wraps any number of static declarations and makes them thread local.
/// Each static may be public or private, and attributes are allowed. Example:
/// Publicity and attributes for each static are allowed. Example:
///
/// ```
/// use std::cell::RefCell;
@ -124,37 +128,26 @@ impl<T: 'static> fmt::Debug for LocalKey<T> { @@ -124,37 +128,26 @@ impl<T: 'static> fmt::Debug for LocalKey<T> {
/// # fn main() {}
/// ```
///
/// See [LocalKey documentation](thread/struct.LocalKey.html) for more
/// See [LocalKey documentation][`std::thread::LocalKey`] for more
/// information.
///
/// [`std::thread::LocalKey`]: ../std/thread/struct.LocalKey.html
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_unstable]
macro_rules! thread_local {
// rule 0: empty (base case for the recursion)
// empty (base case for the recursion)
() => {};
// rule 1: process multiple declarations where the first one is private
($(#[$attr:meta])* static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
thread_local!($(#[$attr])* static $name: $t = $init); // go to rule 2
thread_local!($($rest)*);
);
// rule 2: handle a single private declaration
($(#[$attr:meta])* static $name:ident: $t:ty = $init:expr) => (
$(#[$attr])* static $name: $crate::thread::LocalKey<$t> =
__thread_local_inner!($t, $init);
);
// rule 3: handle multiple declarations where the first one is public
($(#[$attr:meta])* pub static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
thread_local!($(#[$attr])* pub static $name: $t = $init); // go to rule 4
// process multiple declarations
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
thread_local!($($rest)*);
);
// rule 4: handle a single public declaration
($(#[$attr:meta])* pub static $name:ident: $t:ty = $init:expr) => (
$(#[$attr])* pub static $name: $crate::thread::LocalKey<$t> =
__thread_local_inner!($t, $init);
// handle a single declaration
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
);
}
@ -165,27 +158,29 @@ macro_rules! thread_local { @@ -165,27 +158,29 @@ macro_rules! thread_local {
#[macro_export]
#[allow_internal_unstable]
macro_rules! __thread_local_inner {
($t:ty, $init:expr) => {{
fn __init() -> $t { $init }
fn __getit() -> $crate::option::Option<
&'static $crate::cell::UnsafeCell<
$crate::option::Option<$t>>>
{
#[thread_local]
#[cfg(target_thread_local)]
static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
$crate::thread::__FastLocalKeyInner::new();
#[cfg(not(target_thread_local))]
static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
$crate::thread::__OsLocalKeyInner::new();
__KEY.get()
}
($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
$(#[$attr])* $vis static $name: $crate::thread::LocalKey<$t> = {
fn __init() -> $t { $init }
fn __getit() -> $crate::option::Option<
&'static $crate::cell::UnsafeCell<
$crate::option::Option<$t>>>
{
#[thread_local]
#[cfg(target_thread_local)]
static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
$crate::thread::__FastLocalKeyInner::new();
#[cfg(not(target_thread_local))]
static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
$crate::thread::__OsLocalKeyInner::new();
__KEY.get()
}
$crate::thread::LocalKey::new(__getit, __init)
}}
$crate::thread::LocalKey::new(__getit, __init)
};
}
}
/// Indicator of the state of a thread local storage key.
@ -195,11 +190,13 @@ macro_rules! __thread_local_inner { @@ -195,11 +190,13 @@ macro_rules! __thread_local_inner {
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum LocalKeyState {
/// All keys are in this state whenever a thread starts. Keys will
/// transition to the `Valid` state once the first call to `with` happens
/// transition to the `Valid` state once the first call to [`with`] happens
/// and the initialization expression succeeds.
///
/// Keys in the `Uninitialized` state will yield a reference to the closure
/// passed to `with` so long as the initialization routine does not panic.
/// passed to [`with`] so long as the initialization routine does not panic.
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
Uninitialized,
/// Once a key has been accessed successfully, it will enter the `Valid`
@ -208,7 +205,9 @@ pub enum LocalKeyState { @@ -208,7 +205,9 @@ pub enum LocalKeyState {
/// `Destroyed` state.
///
/// Keys in the `Valid` state will be guaranteed to yield a reference to the
/// closure passed to `with`.
/// closure passed to [`with`].
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
Valid,
/// When a thread exits, the destructors for keys will be run (if
@ -216,10 +215,38 @@ pub enum LocalKeyState { @@ -216,10 +215,38 @@ pub enum LocalKeyState {
/// destructor has run, a key is in the `Destroyed` state.
///
/// Keys in the `Destroyed` states will trigger a panic when accessed via
/// `with`.
/// [`with`].
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
Destroyed,
}
/// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]
pub struct AccessError {
_private: (),
}
#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]
impl fmt::Debug for AccessError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("AccessError").finish()
}
}
#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]
impl fmt::Display for AccessError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt("already destroyed", f)
}
}
impl<T: 'static> LocalKey<T> {
#[doc(hidden)]
#[unstable(feature = "thread_local_internals",
@ -246,15 +273,8 @@ impl<T: 'static> LocalKey<T> { @@ -246,15 +273,8 @@ impl<T: 'static> LocalKey<T> {
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with<F, R>(&'static self, f: F) -> R
where F: FnOnce(&T) -> R {
unsafe {
let slot = (self.inner)();
let slot = slot.expect("cannot access a TLS value during or \
after it is destroyed");
f(match *slot.get() {
Some(ref inner) => inner,
None => self.init(slot),
})
}
self.try_with(f).expect("cannot access a TLS value during or \
after it is destroyed")
}
unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
@ -283,23 +303,26 @@ impl<T: 'static> LocalKey<T> { @@ -283,23 +303,26 @@ impl<T: 'static> LocalKey<T> {
/// Query the current state of this key.
///
/// A key is initially in the `Uninitialized` state whenever a thread
/// starts. It will remain in this state up until the first call to `with`
/// starts. It will remain in this state up until the first call to [`with`]
/// within a thread has run the initialization expression successfully.
///
/// Once the initialization expression succeeds, the key transitions to the
/// `Valid` state which will guarantee that future calls to `with` will
/// `Valid` state which will guarantee that future calls to [`with`] will
/// succeed within the thread.
///
/// When a thread exits, each key will be destroyed in turn, and as keys are
/// destroyed they will enter the `Destroyed` state just before the
/// destructor starts to run. Keys may remain in the `Destroyed` state after
/// destruction has completed. Keys without destructors (e.g. with types
/// that are `Copy`), may never enter the `Destroyed` state.
/// that are [`Copy`]), may never enter the `Destroyed` state.
///
/// Keys in the `Uninitialized` state can be accessed so long as the
/// initialization does not panic. Keys in the `Valid` state are guaranteed
/// to be able to be accessed. Keys in the `Destroyed` state will panic on
/// any call to `with`.
/// any call to [`with`].
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
/// [`Copy`]: ../../std/marker/trait.Copy.html
#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]
@ -316,6 +339,108 @@ impl<T: 'static> LocalKey<T> { @@ -316,6 +339,108 @@ impl<T: 'static> LocalKey<T> {
}
}
}
/// Acquires a reference to the value in this TLS key.
///
/// This will lazily initialize the value if this thread has not referenced
/// this key yet. If the key has been destroyed (which may happen if this is called
/// in a destructor), this function will return a ThreadLocalError.
///
/// # Panics
///
/// This function will still `panic!()` if the key is uninitialized and the
/// key's initializer panics.
#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]
pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
where F: FnOnce(&T) -> R {
unsafe {
let slot = (self.inner)().ok_or(AccessError {
_private: (),
})?;
Ok(f(match *slot.get() {
Some(ref inner) => inner,
None => self.init(slot),
}))
}
}
}
#[doc(hidden)]
#[cfg(target_thread_local)]
pub mod fast {
use cell::{Cell, UnsafeCell};
use fmt;
use mem;
use ptr;
use sys::fast_thread_local::{register_dtor, requires_move_before_drop};
pub struct Key<T> {
inner: UnsafeCell<Option<T>>,
// Metadata to keep track of the state of the destructor. Remember that
// these variables are thread-local, not global.
dtor_registered: Cell<bool>,
dtor_running: Cell<bool>,
}
impl<T> fmt::Debug for Key<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Key { .. }")
}
}
unsafe impl<T> ::marker::Sync for Key<T> { }
impl<T> Key<T> {
pub const fn new() -> Key<T> {
Key {
inner: UnsafeCell::new(None),
dtor_registered: Cell::new(false),
dtor_running: Cell::new(false)
}
}
pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
unsafe {
if mem::needs_drop::<T>() && self.dtor_running.get() {
return None
}
self.register_dtor();
}
Some(&self.inner)
}
unsafe fn register_dtor(&self) {
if !mem::needs_drop::<T>() || self.dtor_registered.get() {
return
}
register_dtor(self as *const _ as *mut u8,
destroy_value::<T>);
self.dtor_registered.set(true);
}
}
unsafe extern fn destroy_value<T>(ptr: *mut u8) {
let ptr = ptr as *mut Key<T>;
// Right before we run the user destructor be sure to flag the
// destructor as running for this thread so calls to `get` will return
// `None`.
(*ptr).dtor_running.set(true);
// Some implementations may require us to move the value before we drop
// it as it could get re-initialized in-place during destruction.
//
// Hence, we use `ptr::read` on those platforms (to move to a "safe"
// location) instead of drop_in_place.
if requires_move_before_drop() {
ptr::read((*ptr).inner.get());
} else {
ptr::drop_in_place((*ptr).inner.get());
}
}
}
#[doc(hidden)]
@ -363,8 +488,8 @@ pub mod os { @@ -363,8 +488,8 @@ pub mod os {
return Some(&(*ptr).value);
}
// If the lookup returned null, we haven't initialized our own local
// copy, so do that now.
// If the lookup returned null, we haven't initialized our own
// local copy, so do that now.
let ptr: Box<Value<T>> = box Value {
key: self,
value: UnsafeCell::new(None),
@ -376,7 +501,7 @@ pub mod os { @@ -376,7 +501,7 @@ pub mod os {
}
}
pub unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
// The OS TLS ensures that this key contains a NULL value when this
// destructor starts to run. We set it back to a sentinel value of 1 to
// ensure that any future calls to `get` for this thread will return
@ -524,9 +649,9 @@ mod tests { @@ -524,9 +649,9 @@ mod tests {
}
// Note that this test will deadlock if TLS destructors aren't run (this
// requires the destructor to be run to pass the test). OSX has a known bug
// requires the destructor to be run to pass the test). macOS has a known bug
// where dtors-in-dtors may cancel other destructors, so we just ignore this
// test on OSX.
// test on macOS.
#[test]
#[cfg_attr(target_os = "macos", ignore)]
fn dtors_in_dtors_in_dtors() {

494
ctr-std/src/thread/mod.rs

@ -66,7 +66,7 @@ @@ -66,7 +66,7 @@
//! let res = child.join();
//! ```
//!
//! The [`join`] method returns a [`Result`] containing [`Ok`] of the final
//! The [`join`] method returns a [`thread::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.
//!
@ -90,47 +90,12 @@ @@ -90,47 +90,12 @@
//! two ways:
//!
//! * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`]
//! function, and calling [`thread()`] on the [`JoinHandle`].
//! * By requesting the current thread, using the [`thread::current()`] function.
//! function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
//! * By requesting the current thread, using the [`thread::current`] function.
//!
//! The [`thread::current()`] function is available even for threads not spawned
//! The [`thread::current`] function is available even for threads not spawned
//! by the APIs of this module.
//!
//! ## Blocking support: park and unpark
//!
//! Every thread is equipped with some basic low-level blocking support, via the
//! [`thread::park()`][`park()`] function and [`thread::Thread::unpark()`][`unpark()`]
//! 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:
//!
//! * 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.
//!
//! 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.
//!
//! * It can be implemented very efficiently on many platforms.
//!
//! ## Thread-local storage
//!
//! This module also provides an implementation of thread-local storage for Rust
@ -151,18 +116,19 @@ @@ -151,18 +116,19 @@
//! [`Arc`]: ../../std/sync/struct.Arc.html
//! [`spawn`]: ../../std/thread/fn.spawn.html
//! [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
//! [`thread()`]: ../../std/thread/struct.JoinHandle.html#method.thread
//! [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
//! [`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
//! [`thread::current()`]: ../../std/thread/fn.spawn.html
//! [`thread::current`]: ../../std/thread/fn.current.html
//! [`thread::Result`]: ../../std/thread/type.Result.html
//! [`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
//! [`park`]: ../../std/thread/fn.park.html
//! [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
//! [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
//! [`Cell`]: ../cell/struct.Cell.html
//! [`RefCell`]: ../cell/struct.RefCell.html
//! [`thread_local!`]: ../macro.thread_local.html
@ -176,7 +142,7 @@ use ffi::{CStr, CString}; @@ -176,7 +142,7 @@ use ffi::{CStr, CString};
use fmt;
use io;
use panic;
//use panicking;
use panicking;
use str;
use sync::{Mutex, Condvar, Arc};
use sys::thread as imp;
@ -193,7 +159,7 @@ use time::Duration; @@ -193,7 +159,7 @@ use time::Duration;
#[macro_use] mod local;
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::local::{LocalKey, LocalKeyState};
pub use self::local::{LocalKey, LocalKeyState, AccessError};
// 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
@ -206,7 +172,7 @@ pub use self::local::{LocalKey, LocalKeyState}; @@ -206,7 +172,7 @@ pub use self::local::{LocalKey, LocalKeyState};
#[unstable(feature = "libstd_thread_internals", issue = "0")]
#[cfg(target_thread_local)]
#[doc(hidden)] pub use sys::fast_thread_local::Key as __FastLocalKeyInner;
#[doc(hidden)] pub use self::local::fast::Key as __FastLocalKeyInner;
#[unstable(feature = "libstd_thread_internals", issue = "0")]
#[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
@ -214,8 +180,33 @@ pub use self::local::{LocalKey, LocalKeyState}; @@ -214,8 +180,33 @@ pub use self::local::{LocalKey, LocalKeyState};
// Builder
////////////////////////////////////////////////////////////////////////////////
/// Thread configuration. Provides detailed control over the properties
/// and behavior of new threads.
/// 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 overridden 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`].
///
/// # Examples
///
@ -230,6 +221,13 @@ pub use self::local::{LocalKey, LocalKeyState}; @@ -230,6 +221,13 @@ pub use self::local::{LocalKey, LocalKeyState};
///
/// handler.join().unwrap();
/// ```
///
/// [`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
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug)]
pub struct Builder {
@ -307,13 +305,16 @@ impl Builder { @@ -307,13 +305,16 @@ impl Builder {
self
}
/// Spawns a new thread, and returns a join handle for it.
/// Spawns a new thread by taking ownership of the `Builder`, and returns an
/// [`io::Result`] to its [`JoinHandle`].
///
/// The child thread may outlive the parent (unless the parent thread
/// The spawned thread may outlive the caller (unless the caller thread
/// is the main thread; the whole process is terminated when the main
/// thread finishes). The join handle can be used to block on
/// termination of the child thread, including recovering its panics.
///
/// For a more complete documentation see [`thread::spawn`][`spawn`].
///
/// # Errors
///
/// Unlike the [`spawn`] free function, this method yields an
@ -322,6 +323,7 @@ impl Builder { @@ -322,6 +323,7 @@ impl Builder {
///
/// [`spawn`]: ../../std/thread/fn.spawn.html
/// [`io::Result`]: ../../std/io/type.Result.html
/// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
///
/// # Examples
///
@ -357,6 +359,11 @@ impl Builder { @@ -357,6 +359,11 @@ impl Builder {
}
unsafe {
thread_info::set(imp::guard::current(), their_thread);
#[cfg(feature = "backtrace")]
let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
::sys_common::backtrace::__rust_begin_short_backtrace(f)
}));
#[cfg(not(feature = "backtrace"))]
let try_result = panic::catch_unwind(panic::AssertUnwindSafe(f));
*their_packet.get() = Some(try_result);
}
@ -386,19 +393,39 @@ impl Builder { @@ -386,19 +393,39 @@ impl Builder {
/// panics, [`join`] will return an [`Err`] containing the argument given to
/// [`panic`].
///
/// 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.
///
/// 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.
///
/// # Panics
///
/// Panics if the OS fails to create a thread; use [`Builder::spawn`]
/// to recover from such errors.
///
/// [`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
///
/// # Examples
///
/// Creating a thread.
///
/// ```
/// use std::thread;
///
@ -408,6 +435,56 @@ impl Builder { @@ -408,6 +435,56 @@ impl Builder {
///
/// handler.join().unwrap();
/// ```
///
/// As mentioned in the module documentation, threads are usually made to
/// communicate using [`channels`], here is how it usually looks.
///
/// 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 || {
/// let _ = tx.send("Hello, thread".to_owned());
/// });
///
/// let receiver = thread::spawn(move || {
/// println!("{}", rx.recv().unwrap());
/// });
///
/// let _ = sender.join();
/// let _ = receiver.join();
/// ```
///
/// 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();
/// println!("{}", result);
/// ```
///
/// [`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
/// [`Builder`]: ../../std/thread/struct.Builder.html
/// [`Send`]: ../../std/marker/trait.Send.html
/// [`Sync`]: ../../std/marker/trait.Sync.html
#[stable(feature = "rust1", since = "1.0.0")]
pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
@ -443,6 +520,23 @@ pub fn current() -> Thread { @@ -443,6 +520,23 @@ pub fn current() -> Thread {
/// Cooperatively gives up a timeslice to the OS scheduler.
///
/// 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 usually 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.
///
/// # Examples
///
/// ```
@ -450,6 +544,12 @@ pub fn current() -> Thread { @@ -450,6 +544,12 @@ pub fn current() -> Thread {
///
/// thread::yield_now();
/// ```
///
/// [`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
#[stable(feature = "rust1", since = "1.0.0")]
pub fn yield_now() {
imp::Thread::yield_now()
@ -457,6 +557,16 @@ pub fn yield_now() { @@ -457,6 +557,16 @@ pub fn yield_now() {
/// Determines whether the current thread is unwinding because of panic.
///
/// 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).
///
/// # Examples
///
/// ```should_panic
@ -485,11 +595,12 @@ pub fn yield_now() { @@ -485,11 +595,12 @@ pub fn yield_now() {
/// panic!()
/// }
/// ```
// We don't have stack unwinding on the 3DS, so we can leave this as false for now
///
/// [Mutex]: ../../std/sync/struct.Mutex.html
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn panicking() -> bool {
false
panicking::panicking()
}
/// Puts the current thread to sleep for the specified amount of time.
@ -547,23 +658,72 @@ pub fn sleep(dur: Duration) { @@ -547,23 +658,72 @@ pub fn sleep(dur: Duration) {
/// Blocks unless or until the current thread's token is made available.
///
/// 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.
/// 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
/// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
/// 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:
///
/// [unpark]: struct.Thread.html#method.unpark
/// * 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.
///
/// In other words, each [`Thread`] acts a bit like a spinlock that can be
/// locked and unlocked using `park` and `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).
/// find it, and then `park`ing. When some desired condition is met, another
/// thread calls [`unpark`] on the handle.
///
/// A call to `park` does not guarantee that the thread will remain parked
/// forever, and callers should be prepared for this possibility.
/// The motivation for this design is twofold:
///
/// See the [module documentation][thread] for more detail.
/// * It avoids the need to allocate mutexes and condvars when building new
/// synchronization primitives; the threads already provide basic
/// blocking/signaling.
///
/// [thread]: index.html
/// * It can be implemented very efficiently on many platforms.
///
/// # Examples
///
/// ```
/// use std::thread;
/// use std::time::Duration;
///
/// 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
//
// The implementation currently uses the trivial strategy of a Mutex+Condvar
// with wakeup flag, which does not actually allow spurious wakeups. In the
@ -580,21 +740,21 @@ pub fn park() { @@ -580,21 +740,21 @@ pub fn park() {
*guard = false;
}
/// Use [park_timeout].
/// Use [`park_timeout`].
///
/// 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 `ms`. This method
/// should not be used for precise timing due to anomalies such as
/// 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 `ms` long.
///
/// See the [module documentation][thread] for more detail.
/// See the [park documentation][`park`] for more detail.
///
/// [thread]: index.html
/// [park_timeout]: fn.park_timeout.html
/// [`park_timeout`]: fn.park_timeout.html
/// [`park`]: ../../std/thread/fn.park.html
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
pub fn park_timeout_ms(ms: u32) {
@ -604,13 +764,13 @@ pub fn park_timeout_ms(ms: u32) { @@ -604,13 +764,13 @@ pub fn park_timeout_ms(ms: u32) {
/// 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
/// The semantics of this function are equivalent to [`park`][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.
/// See the [park documentation][park] for more details.
///
/// # Platform behavior
///
@ -627,14 +787,20 @@ pub fn park_timeout_ms(ms: u32) { @@ -627,14 +787,20 @@ pub fn park_timeout_ms(ms: u32) {
///
/// 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);
/// let mut timeout_remaining = timeout;
/// loop {
/// park_timeout(timeout_remaining);
/// let elapsed = beginning_park.elapsed();
/// if elapsed >= timeout {
/// break;
/// }
/// println!("restarting park_timeout after {:?}", elapsed);
/// timeout_remaining = timeout - elapsed;
/// }
/// ```
///
/// [park]: fn.park.html
#[stable(feature = "park_timeout", since = "1.4.0")]
pub fn park_timeout(dur: Duration) {
let thread = current();
@ -653,27 +819,23 @@ pub fn park_timeout(dur: Duration) { @@ -653,27 +819,23 @@ pub fn park_timeout(dur: Duration) {
/// A unique identifier for a running thread.
///
/// A `ThreadId` is an opaque object that has a unique value for each thread
/// that creates one. `ThreadId`s do not correspond to a thread's system-
/// designated identifier.
/// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
/// system-designated identifier.
///
/// # Examples
///
/// ```
/// #![feature(thread_id)]
///
/// use std::thread;
///
/// let handler = thread::Builder::new()
/// .spawn(|| {
/// let thread = thread::current();
/// let thread_id = thread.id();
/// })
/// .unwrap();
/// let other_thread = thread::spawn(|| {
/// thread::current().id()
/// });
///
/// handler.join().unwrap();
/// let other_thread_id = other_thread.join().unwrap();
/// assert!(thread::current().id() != other_thread_id);
/// ```
#[unstable(feature = "thread_id", issue = "21507")]
#[derive(Eq, PartialEq, Copy, Clone)]
#[stable(feature = "thread_id", since = "1.19.0")]
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
pub struct ThreadId(u64);
impl ThreadId {
@ -702,13 +864,6 @@ impl ThreadId { @@ -702,13 +864,6 @@ impl ThreadId {
}
}
#[unstable(feature = "thread_id", issue = "21507")]
impl fmt::Debug for ThreadId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("ThreadId { .. }")
}
}
////////////////////////////////////////////////////////////////////////////////
// Thread
////////////////////////////////////////////////////////////////////////////////
@ -725,28 +880,31 @@ struct Inner { @@ -725,28 +880,31 @@ struct Inner {
#[stable(feature = "rust1", since = "1.0.0")]
/// A handle to a thread.
///
/// # Examples
/// Threads are represented via the `Thread` type, which you can get in one of
/// two ways:
///
/// ```
/// use std::thread;
/// * 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.
///
/// let handler = thread::Builder::new()
/// .name("foo".into())
/// .spawn(|| {
/// let thread = thread::current();
/// println!("thread name: {}", thread.name().unwrap());
/// })
/// .unwrap();
/// The [`thread::current`] function is available even for threads not spawned
/// by the APIs of this module.
///
/// handler.join().unwrap();
/// ```
/// There is usually 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.
///
/// [`Builder`]: ../../std/thread/struct.Builder.html
/// [`spawn`]: ../../std/thread/fn.spawn.html
pub struct Thread {
inner: Arc<Inner>,
}
impl Thread {
// Used only internally to construct a thread object without spawning
fn new(name: Option<String>) -> Thread {
pub(crate) fn new(name: Option<String>) -> Thread {
let cname = name.map(|n| {
CString::new(n).expect("thread name may not contain interior null bytes")
});
@ -762,22 +920,36 @@ impl Thread { @@ -762,22 +920,36 @@ impl Thread {
/// Atomically makes the handle's token available if it is not already.
///
/// See the module doc for more detail.
/// Every thread is equipped with some basic low-level blocking support, via
/// the [`park`][park] function and the `unpark()` method. These can be
/// used as a more CPU-efficient implementation of a spinlock.
///
/// See the [park documentation][park] for more details.
///
/// # Examples
///
/// ```
/// use std::thread;
/// use std::time::Duration;
///
/// let handler = thread::Builder::new()
/// let parked_thread = thread::Builder::new()
/// .spawn(|| {
/// let thread = thread::current();
/// thread.unpark();
/// println!("Parking thread");
/// thread::park();
/// println!("Thread unparked");
/// })
/// .unwrap();
///
/// handler.join().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();
/// ```
///
/// [park]: fn.park.html
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unpark(&self) {
let mut guard = self.inner.lock.lock().unwrap();
@ -792,20 +964,16 @@ impl Thread { @@ -792,20 +964,16 @@ impl Thread {
/// # Examples
///
/// ```
/// #![feature(thread_id)]
///
/// use std::thread;
///
/// let handler = thread::Builder::new()
/// .spawn(|| {
/// let thread = thread::current();
/// println!("thread id: {:?}", thread.id());
/// })
/// .unwrap();
/// let other_thread = thread::spawn(|| {
/// thread::current().id()
/// });
///
/// handler.join().unwrap();
/// let other_thread_id = other_thread.join().unwrap();
/// assert!(thread::current().id() != other_thread_id);
/// ```
#[unstable(feature = "thread_id", issue = "21507")]
#[stable(feature = "thread_id", since = "1.19.0")]
pub fn id(&self) -> ThreadId {
self.inner.id
}
@ -859,18 +1027,35 @@ impl fmt::Debug for Thread { @@ -859,18 +1027,35 @@ impl fmt::Debug for Thread {
}
}
// a hack to get around privacy restrictions
impl thread_info::NewThread for Thread {
fn new(name: Option<String>) -> Thread { Thread::new(name) }
}
////////////////////////////////////////////////////////////////////////////////
// JoinHandle
////////////////////////////////////////////////////////////////////////////////
/// A specialized [`Result`] type for threads.
///
/// Indicates the manner in which a thread exited.
///
/// A thread that completes without panicking is considered to exit successfully.
///
/// # 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
#[stable(feature = "rust1", since = "1.0.0")]
pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
@ -909,11 +1094,12 @@ impl<T> JoinInner<T> { @@ -909,11 +1094,12 @@ impl<T> JoinInner<T> {
/// An owned permission to join on a thread (block on its termination).
///
/// A `JoinHandle` *detaches* the child thread when it is dropped.
/// 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.
///
/// Due to platform restrictions, it is not possible to [`Clone`] this
/// handle: the ability to join a child thread is a uniquely-owned
/// permission.
/// handle: the ability to join a thread is a uniquely-owned permission.
///
/// This `struct` is created by the [`thread::spawn`] function and the
/// [`thread::Builder::spawn`] method.
@ -942,6 +1128,30 @@ impl<T> JoinInner<T> { @@ -942,6 +1128,30 @@ impl<T> JoinInner<T> {
/// }).unwrap();
/// ```
///
/// 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));
/// ```
///
/// [`Clone`]: ../../std/clone/trait.Clone.html
/// [`thread::spawn`]: fn.spawn.html
/// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
@ -954,8 +1164,6 @@ impl<T> JoinHandle<T> { @@ -954,8 +1164,6 @@ impl<T> JoinHandle<T> {
/// # Examples
///
/// ```
/// #![feature(thread_id)]
///
/// use std::thread;
///
/// let builder = thread::Builder::new();

Loading…
Cancel
Save