2014-01-15 11:34:05 -06:00
|
|
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
|
2013-04-21 18:28:17 -05:00
|
|
|
// 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.
|
|
|
|
|
|
|
|
//! Language-level runtime services that should reasonably expected
|
2014-09-30 16:09:46 -05:00
|
|
|
//! to be available 'everywhere'. Unwinding, local storage, and logging.
|
|
|
|
//! Even a 'freestanding' Rust would likely want to implement this.
|
2013-04-21 18:28:17 -05:00
|
|
|
|
2014-11-06 02:05:53 -06:00
|
|
|
pub use self::BlockedTask::*;
|
|
|
|
use self::TaskState::*;
|
|
|
|
|
2014-11-23 21:21:17 -06:00
|
|
|
use any::Any;
|
|
|
|
use boxed::Box;
|
|
|
|
use sync::Arc;
|
|
|
|
use sync::atomic::{AtomicUint, SeqCst};
|
|
|
|
use iter::{IteratorExt, Take};
|
|
|
|
use kinds::marker;
|
|
|
|
use mem;
|
|
|
|
use ops::FnMut;
|
2014-08-12 22:31:30 -05:00
|
|
|
use core::prelude::{Clone, Drop, Err, Iterator, None, Ok, Option, Send, Some};
|
|
|
|
use core::prelude::{drop};
|
2014-11-23 21:21:17 -06:00
|
|
|
use str::SendStr;
|
2014-11-26 09:10:52 -06:00
|
|
|
use thunk::Thunk;
|
2013-12-12 20:01:59 -06:00
|
|
|
|
2014-11-23 21:21:17 -06:00
|
|
|
use rt;
|
|
|
|
use rt::mutex::NativeMutex;
|
|
|
|
use rt::local::Local;
|
|
|
|
use rt::thread::{mod, Thread};
|
|
|
|
use sys_common::stack;
|
|
|
|
use rt::unwind;
|
|
|
|
use rt::unwind::Unwinder;
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// State associated with Rust threads
|
2014-06-13 18:03:41 -05:00
|
|
|
///
|
2014-11-14 15:40:34 -06:00
|
|
|
/// This structure is currently undergoing major changes, and is
|
|
|
|
/// likely to be move/be merged with a `Thread` structure.
|
2013-05-19 03:04:01 -05:00
|
|
|
pub struct Task {
|
2014-03-27 17:09:47 -05:00
|
|
|
pub unwinder: Unwinder,
|
|
|
|
pub death: Death,
|
|
|
|
pub name: Option<SendStr>,
|
2013-12-12 20:01:59 -06:00
|
|
|
|
2014-07-24 00:48:04 -05:00
|
|
|
state: TaskState,
|
2014-11-14 15:40:34 -06:00
|
|
|
lock: NativeMutex, // native synchronization
|
|
|
|
awoken: bool, // used to prevent spurious wakeups
|
|
|
|
|
|
|
|
// This field holds the known bounds of the stack in (lo, hi) form. Not all
|
2014-12-26 15:04:27 -06:00
|
|
|
// native threads necessarily know their precise bounds, hence this is
|
2014-11-14 15:40:34 -06:00
|
|
|
// optional.
|
|
|
|
stack_bounds: (uint, uint),
|
|
|
|
|
|
|
|
stack_guard: uint
|
2013-07-19 16:25:05 -05:00
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
// Once a thread has entered the `Armed` state it must be destroyed via `drop`,
|
2014-07-24 00:48:04 -05:00
|
|
|
// and no other method. This state is used to track this transition.
|
|
|
|
#[deriving(PartialEq)]
|
|
|
|
enum TaskState {
|
|
|
|
New,
|
|
|
|
Armed,
|
|
|
|
Destroyed,
|
|
|
|
}
|
|
|
|
|
std: Extract librustrt out of libstd
As part of the libstd facade efforts, this commit extracts the runtime interface
out of the standard library into a standalone crate, librustrt. This crate will
provide the following services:
* Definition of the rtio interface
* Definition of the Runtime interface
* Implementation of the Task structure
* Implementation of task-local-data
* Implementation of task failure via unwinding via libunwind
* Implementation of runtime initialization and shutdown
* Implementation of thread-local-storage for the local rust Task
Notably, this crate avoids the following services:
* Thread creation and destruction. The crate does not require the knowledge of
an OS threading system, and as a result it seemed best to leave out the
`rt::thread` module from librustrt. The librustrt module does depend on
mutexes, however.
* Implementation of backtraces. There is no inherent requirement for the runtime
to be able to generate backtraces. As will be discussed later, this
functionality continues to live in libstd rather than librustrt.
As usual, a number of architectural changes were required to make this crate
possible. Users of "stable" functionality will not be impacted by this change,
but users of the `std::rt` module will likely note the changes. A list of
architectural changes made is:
* The stdout/stderr handles no longer live directly inside of the `Task`
structure. This is a consequence of librustrt not knowing about `std::io`.
These two handles are now stored inside of task-local-data.
The handles were originally stored inside of the `Task` for perf reasons, and
TLD is not currently as fast as it could be. For comparison, 100k prints goes
from 59ms to 68ms (a 15% slowdown). This appeared to me to be an acceptable
perf loss for the successful extraction of a librustrt crate.
* The `rtio` module was forced to duplicate more functionality of `std::io`. As
the module no longer depends on `std::io`, `rtio` now defines structures such
as socket addresses, addrinfo fiddly bits, etc. The primary change made was
that `rtio` now defines its own `IoError` type. This type is distinct from
`std::io::IoError` in that it does not have an enum for what error occurred,
but rather a platform-specific error code.
The native and green libraries will be updated in later commits for this
change, and the bulk of this effort was put behind updating the two libraries
for this change (with `rtio`).
* Printing a message on task failure (along with the backtrace) continues to
live in libstd, not in librustrt. This is a consequence of the above decision
to move the stdout/stderr handles to TLD rather than inside the `Task` itself.
The unwinding API now supports registration of global callback functions which
will be invoked when a task fails, allowing for libstd to register a function
to print a message and a backtrace.
The API for registering a callback is experimental and unsafe, as the
ramifications of running code on unwinding is pretty hairy.
* The `std::unstable::mutex` module has moved to `std::rt::mutex`.
* The `std::unstable::sync` module has been moved to `std::rt::exclusive` and
the type has been rewritten to not internally have an Arc and to have an RAII
guard structure when locking. Old code should stop using `Exclusive` in favor
of the primitives in `libsync`, but if necessary, old code should port to
`Arc<Exclusive<T>>`.
* The local heap has been stripped down to have fewer debugging options. None of
these were tested, and none of these have been used in a very long time.
[breaking-change]
2014-06-03 21:11:49 -05:00
|
|
|
pub struct TaskOpts {
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Invoke this procedure with the result of the thread when it finishes.
|
2014-11-26 09:10:52 -06:00
|
|
|
pub on_exit: Option<Thunk<Result>>,
|
2014-12-26 15:04:27 -06:00
|
|
|
/// A name for the thread-to-be, for identification in panic messages
|
std: Extract librustrt out of libstd
As part of the libstd facade efforts, this commit extracts the runtime interface
out of the standard library into a standalone crate, librustrt. This crate will
provide the following services:
* Definition of the rtio interface
* Definition of the Runtime interface
* Implementation of the Task structure
* Implementation of task-local-data
* Implementation of task failure via unwinding via libunwind
* Implementation of runtime initialization and shutdown
* Implementation of thread-local-storage for the local rust Task
Notably, this crate avoids the following services:
* Thread creation and destruction. The crate does not require the knowledge of
an OS threading system, and as a result it seemed best to leave out the
`rt::thread` module from librustrt. The librustrt module does depend on
mutexes, however.
* Implementation of backtraces. There is no inherent requirement for the runtime
to be able to generate backtraces. As will be discussed later, this
functionality continues to live in libstd rather than librustrt.
As usual, a number of architectural changes were required to make this crate
possible. Users of "stable" functionality will not be impacted by this change,
but users of the `std::rt` module will likely note the changes. A list of
architectural changes made is:
* The stdout/stderr handles no longer live directly inside of the `Task`
structure. This is a consequence of librustrt not knowing about `std::io`.
These two handles are now stored inside of task-local-data.
The handles were originally stored inside of the `Task` for perf reasons, and
TLD is not currently as fast as it could be. For comparison, 100k prints goes
from 59ms to 68ms (a 15% slowdown). This appeared to me to be an acceptable
perf loss for the successful extraction of a librustrt crate.
* The `rtio` module was forced to duplicate more functionality of `std::io`. As
the module no longer depends on `std::io`, `rtio` now defines structures such
as socket addresses, addrinfo fiddly bits, etc. The primary change made was
that `rtio` now defines its own `IoError` type. This type is distinct from
`std::io::IoError` in that it does not have an enum for what error occurred,
but rather a platform-specific error code.
The native and green libraries will be updated in later commits for this
change, and the bulk of this effort was put behind updating the two libraries
for this change (with `rtio`).
* Printing a message on task failure (along with the backtrace) continues to
live in libstd, not in librustrt. This is a consequence of the above decision
to move the stdout/stderr handles to TLD rather than inside the `Task` itself.
The unwinding API now supports registration of global callback functions which
will be invoked when a task fails, allowing for libstd to register a function
to print a message and a backtrace.
The API for registering a callback is experimental and unsafe, as the
ramifications of running code on unwinding is pretty hairy.
* The `std::unstable::mutex` module has moved to `std::rt::mutex`.
* The `std::unstable::sync` module has been moved to `std::rt::exclusive` and
the type has been rewritten to not internally have an Arc and to have an RAII
guard structure when locking. Old code should stop using `Exclusive` in favor
of the primitives in `libsync`, but if necessary, old code should port to
`Arc<Exclusive<T>>`.
* The local heap has been stripped down to have fewer debugging options. None of
these were tested, and none of these have been used in a very long time.
[breaking-change]
2014-06-03 21:11:49 -05:00
|
|
|
pub name: Option<SendStr>,
|
2014-12-26 15:04:27 -06:00
|
|
|
/// The size of the stack for the spawned thread
|
std: Extract librustrt out of libstd
As part of the libstd facade efforts, this commit extracts the runtime interface
out of the standard library into a standalone crate, librustrt. This crate will
provide the following services:
* Definition of the rtio interface
* Definition of the Runtime interface
* Implementation of the Task structure
* Implementation of task-local-data
* Implementation of task failure via unwinding via libunwind
* Implementation of runtime initialization and shutdown
* Implementation of thread-local-storage for the local rust Task
Notably, this crate avoids the following services:
* Thread creation and destruction. The crate does not require the knowledge of
an OS threading system, and as a result it seemed best to leave out the
`rt::thread` module from librustrt. The librustrt module does depend on
mutexes, however.
* Implementation of backtraces. There is no inherent requirement for the runtime
to be able to generate backtraces. As will be discussed later, this
functionality continues to live in libstd rather than librustrt.
As usual, a number of architectural changes were required to make this crate
possible. Users of "stable" functionality will not be impacted by this change,
but users of the `std::rt` module will likely note the changes. A list of
architectural changes made is:
* The stdout/stderr handles no longer live directly inside of the `Task`
structure. This is a consequence of librustrt not knowing about `std::io`.
These two handles are now stored inside of task-local-data.
The handles were originally stored inside of the `Task` for perf reasons, and
TLD is not currently as fast as it could be. For comparison, 100k prints goes
from 59ms to 68ms (a 15% slowdown). This appeared to me to be an acceptable
perf loss for the successful extraction of a librustrt crate.
* The `rtio` module was forced to duplicate more functionality of `std::io`. As
the module no longer depends on `std::io`, `rtio` now defines structures such
as socket addresses, addrinfo fiddly bits, etc. The primary change made was
that `rtio` now defines its own `IoError` type. This type is distinct from
`std::io::IoError` in that it does not have an enum for what error occurred,
but rather a platform-specific error code.
The native and green libraries will be updated in later commits for this
change, and the bulk of this effort was put behind updating the two libraries
for this change (with `rtio`).
* Printing a message on task failure (along with the backtrace) continues to
live in libstd, not in librustrt. This is a consequence of the above decision
to move the stdout/stderr handles to TLD rather than inside the `Task` itself.
The unwinding API now supports registration of global callback functions which
will be invoked when a task fails, allowing for libstd to register a function
to print a message and a backtrace.
The API for registering a callback is experimental and unsafe, as the
ramifications of running code on unwinding is pretty hairy.
* The `std::unstable::mutex` module has moved to `std::rt::mutex`.
* The `std::unstable::sync` module has been moved to `std::rt::exclusive` and
the type has been rewritten to not internally have an Arc and to have an RAII
guard structure when locking. Old code should stop using `Exclusive` in favor
of the primitives in `libsync`, but if necessary, old code should port to
`Arc<Exclusive<T>>`.
* The local heap has been stripped down to have fewer debugging options. None of
these were tested, and none of these have been used in a very long time.
[breaking-change]
2014-06-03 21:11:49 -05:00
|
|
|
pub stack_size: Option<uint>,
|
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Indicates the manner in which a thread exited.
|
std: Extract librustrt out of libstd
As part of the libstd facade efforts, this commit extracts the runtime interface
out of the standard library into a standalone crate, librustrt. This crate will
provide the following services:
* Definition of the rtio interface
* Definition of the Runtime interface
* Implementation of the Task structure
* Implementation of task-local-data
* Implementation of task failure via unwinding via libunwind
* Implementation of runtime initialization and shutdown
* Implementation of thread-local-storage for the local rust Task
Notably, this crate avoids the following services:
* Thread creation and destruction. The crate does not require the knowledge of
an OS threading system, and as a result it seemed best to leave out the
`rt::thread` module from librustrt. The librustrt module does depend on
mutexes, however.
* Implementation of backtraces. There is no inherent requirement for the runtime
to be able to generate backtraces. As will be discussed later, this
functionality continues to live in libstd rather than librustrt.
As usual, a number of architectural changes were required to make this crate
possible. Users of "stable" functionality will not be impacted by this change,
but users of the `std::rt` module will likely note the changes. A list of
architectural changes made is:
* The stdout/stderr handles no longer live directly inside of the `Task`
structure. This is a consequence of librustrt not knowing about `std::io`.
These two handles are now stored inside of task-local-data.
The handles were originally stored inside of the `Task` for perf reasons, and
TLD is not currently as fast as it could be. For comparison, 100k prints goes
from 59ms to 68ms (a 15% slowdown). This appeared to me to be an acceptable
perf loss for the successful extraction of a librustrt crate.
* The `rtio` module was forced to duplicate more functionality of `std::io`. As
the module no longer depends on `std::io`, `rtio` now defines structures such
as socket addresses, addrinfo fiddly bits, etc. The primary change made was
that `rtio` now defines its own `IoError` type. This type is distinct from
`std::io::IoError` in that it does not have an enum for what error occurred,
but rather a platform-specific error code.
The native and green libraries will be updated in later commits for this
change, and the bulk of this effort was put behind updating the two libraries
for this change (with `rtio`).
* Printing a message on task failure (along with the backtrace) continues to
live in libstd, not in librustrt. This is a consequence of the above decision
to move the stdout/stderr handles to TLD rather than inside the `Task` itself.
The unwinding API now supports registration of global callback functions which
will be invoked when a task fails, allowing for libstd to register a function
to print a message and a backtrace.
The API for registering a callback is experimental and unsafe, as the
ramifications of running code on unwinding is pretty hairy.
* The `std::unstable::mutex` module has moved to `std::rt::mutex`.
* The `std::unstable::sync` module has been moved to `std::rt::exclusive` and
the type has been rewritten to not internally have an Arc and to have an RAII
guard structure when locking. Old code should stop using `Exclusive` in favor
of the primitives in `libsync`, but if necessary, old code should port to
`Arc<Exclusive<T>>`.
* The local heap has been stripped down to have fewer debugging options. None of
these were tested, and none of these have been used in a very long time.
[breaking-change]
2014-06-03 21:11:49 -05:00
|
|
|
///
|
2014-12-26 15:04:27 -06:00
|
|
|
/// A thread that completes without panicking is considered to exit successfully.
|
std: Extract librustrt out of libstd
As part of the libstd facade efforts, this commit extracts the runtime interface
out of the standard library into a standalone crate, librustrt. This crate will
provide the following services:
* Definition of the rtio interface
* Definition of the Runtime interface
* Implementation of the Task structure
* Implementation of task-local-data
* Implementation of task failure via unwinding via libunwind
* Implementation of runtime initialization and shutdown
* Implementation of thread-local-storage for the local rust Task
Notably, this crate avoids the following services:
* Thread creation and destruction. The crate does not require the knowledge of
an OS threading system, and as a result it seemed best to leave out the
`rt::thread` module from librustrt. The librustrt module does depend on
mutexes, however.
* Implementation of backtraces. There is no inherent requirement for the runtime
to be able to generate backtraces. As will be discussed later, this
functionality continues to live in libstd rather than librustrt.
As usual, a number of architectural changes were required to make this crate
possible. Users of "stable" functionality will not be impacted by this change,
but users of the `std::rt` module will likely note the changes. A list of
architectural changes made is:
* The stdout/stderr handles no longer live directly inside of the `Task`
structure. This is a consequence of librustrt not knowing about `std::io`.
These two handles are now stored inside of task-local-data.
The handles were originally stored inside of the `Task` for perf reasons, and
TLD is not currently as fast as it could be. For comparison, 100k prints goes
from 59ms to 68ms (a 15% slowdown). This appeared to me to be an acceptable
perf loss for the successful extraction of a librustrt crate.
* The `rtio` module was forced to duplicate more functionality of `std::io`. As
the module no longer depends on `std::io`, `rtio` now defines structures such
as socket addresses, addrinfo fiddly bits, etc. The primary change made was
that `rtio` now defines its own `IoError` type. This type is distinct from
`std::io::IoError` in that it does not have an enum for what error occurred,
but rather a platform-specific error code.
The native and green libraries will be updated in later commits for this
change, and the bulk of this effort was put behind updating the two libraries
for this change (with `rtio`).
* Printing a message on task failure (along with the backtrace) continues to
live in libstd, not in librustrt. This is a consequence of the above decision
to move the stdout/stderr handles to TLD rather than inside the `Task` itself.
The unwinding API now supports registration of global callback functions which
will be invoked when a task fails, allowing for libstd to register a function
to print a message and a backtrace.
The API for registering a callback is experimental and unsafe, as the
ramifications of running code on unwinding is pretty hairy.
* The `std::unstable::mutex` module has moved to `std::rt::mutex`.
* The `std::unstable::sync` module has been moved to `std::rt::exclusive` and
the type has been rewritten to not internally have an Arc and to have an RAII
guard structure when locking. Old code should stop using `Exclusive` in favor
of the primitives in `libsync`, but if necessary, old code should port to
`Arc<Exclusive<T>>`.
* The local heap has been stripped down to have fewer debugging options. None of
these were tested, and none of these have been used in a very long time.
[breaking-change]
2014-06-03 21:11:49 -05:00
|
|
|
///
|
|
|
|
/// If you wish for this result's delivery to block until all
|
2014-12-26 15:04:27 -06:00
|
|
|
/// children threads complete, recommend using a result future.
|
2014-06-14 13:03:34 -05:00
|
|
|
pub type Result = ::core::result::Result<(), Box<Any + Send>>;
|
std: Extract librustrt out of libstd
As part of the libstd facade efforts, this commit extracts the runtime interface
out of the standard library into a standalone crate, librustrt. This crate will
provide the following services:
* Definition of the rtio interface
* Definition of the Runtime interface
* Implementation of the Task structure
* Implementation of task-local-data
* Implementation of task failure via unwinding via libunwind
* Implementation of runtime initialization and shutdown
* Implementation of thread-local-storage for the local rust Task
Notably, this crate avoids the following services:
* Thread creation and destruction. The crate does not require the knowledge of
an OS threading system, and as a result it seemed best to leave out the
`rt::thread` module from librustrt. The librustrt module does depend on
mutexes, however.
* Implementation of backtraces. There is no inherent requirement for the runtime
to be able to generate backtraces. As will be discussed later, this
functionality continues to live in libstd rather than librustrt.
As usual, a number of architectural changes were required to make this crate
possible. Users of "stable" functionality will not be impacted by this change,
but users of the `std::rt` module will likely note the changes. A list of
architectural changes made is:
* The stdout/stderr handles no longer live directly inside of the `Task`
structure. This is a consequence of librustrt not knowing about `std::io`.
These two handles are now stored inside of task-local-data.
The handles were originally stored inside of the `Task` for perf reasons, and
TLD is not currently as fast as it could be. For comparison, 100k prints goes
from 59ms to 68ms (a 15% slowdown). This appeared to me to be an acceptable
perf loss for the successful extraction of a librustrt crate.
* The `rtio` module was forced to duplicate more functionality of `std::io`. As
the module no longer depends on `std::io`, `rtio` now defines structures such
as socket addresses, addrinfo fiddly bits, etc. The primary change made was
that `rtio` now defines its own `IoError` type. This type is distinct from
`std::io::IoError` in that it does not have an enum for what error occurred,
but rather a platform-specific error code.
The native and green libraries will be updated in later commits for this
change, and the bulk of this effort was put behind updating the two libraries
for this change (with `rtio`).
* Printing a message on task failure (along with the backtrace) continues to
live in libstd, not in librustrt. This is a consequence of the above decision
to move the stdout/stderr handles to TLD rather than inside the `Task` itself.
The unwinding API now supports registration of global callback functions which
will be invoked when a task fails, allowing for libstd to register a function
to print a message and a backtrace.
The API for registering a callback is experimental and unsafe, as the
ramifications of running code on unwinding is pretty hairy.
* The `std::unstable::mutex` module has moved to `std::rt::mutex`.
* The `std::unstable::sync` module has been moved to `std::rt::exclusive` and
the type has been rewritten to not internally have an Arc and to have an RAII
guard structure when locking. Old code should stop using `Exclusive` in favor
of the primitives in `libsync`, but if necessary, old code should port to
`Arc<Exclusive<T>>`.
* The local heap has been stripped down to have fewer debugging options. None of
these were tested, and none of these have been used in a very long time.
[breaking-change]
2014-06-03 21:11:49 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// A handle to a blocked thread. Usually this means having the Box<Task>
|
|
|
|
/// pointer by ownership, but if the thread is killable, a killer can steal it
|
2014-05-05 20:56:44 -05:00
|
|
|
/// at any time.
|
2013-12-12 20:01:59 -06:00
|
|
|
pub enum BlockedTask {
|
2014-05-05 20:56:44 -05:00
|
|
|
Owned(Box<Task>),
|
2014-05-19 19:33:40 -05:00
|
|
|
Shared(Arc<AtomicUint>),
|
2013-06-26 18:41:00 -05:00
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Per-thread state related to thread death, killing, panic, etc.
|
2013-12-12 20:01:59 -06:00
|
|
|
pub struct Death {
|
2014-11-26 09:10:52 -06:00
|
|
|
pub on_exit: Option<Thunk<Result>>,
|
2013-04-21 18:28:17 -05:00
|
|
|
}
|
|
|
|
|
2014-01-14 21:32:24 -06:00
|
|
|
pub struct BlockedTasks {
|
2014-05-19 19:33:40 -05:00
|
|
|
inner: Arc<AtomicUint>,
|
2013-12-12 20:01:59 -06:00
|
|
|
}
|
2013-04-22 19:15:31 -05:00
|
|
|
|
2013-05-19 03:04:01 -05:00
|
|
|
impl Task {
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Creates a new uninitialized thread.
|
2014-11-14 15:40:34 -06:00
|
|
|
pub fn new(stack_bounds: Option<(uint, uint)>, stack_guard: Option<uint>) -> Task {
|
2013-05-19 03:04:01 -05:00
|
|
|
Task {
|
2013-12-12 20:01:59 -06:00
|
|
|
unwinder: Unwinder::new(),
|
2013-07-01 22:24:24 -05:00
|
|
|
death: Death::new(),
|
2014-07-24 00:48:04 -05:00
|
|
|
state: New,
|
2013-07-30 18:20:59 -05:00
|
|
|
name: None,
|
2014-11-14 15:40:34 -06:00
|
|
|
lock: unsafe { NativeMutex::new() },
|
|
|
|
awoken: false,
|
|
|
|
// these *should* get overwritten
|
|
|
|
stack_bounds: stack_bounds.unwrap_or((0, 0)),
|
|
|
|
stack_guard: stack_guard.unwrap_or(0)
|
2013-04-21 18:28:17 -05:00
|
|
|
}
|
|
|
|
}
|
2013-04-22 14:54:03 -05:00
|
|
|
|
2014-11-26 09:10:52 -06:00
|
|
|
pub fn spawn<F>(opts: TaskOpts, f: F)
|
|
|
|
where F : FnOnce(), F : Send
|
|
|
|
{
|
|
|
|
Task::spawn_thunk(opts, Thunk::new(f))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn spawn_thunk(opts: TaskOpts, f: Thunk) {
|
2014-11-14 15:40:34 -06:00
|
|
|
let TaskOpts { name, stack_size, on_exit } = opts;
|
|
|
|
|
|
|
|
let mut task = box Task::new(None, None);
|
|
|
|
task.name = name;
|
|
|
|
task.death.on_exit = on_exit;
|
|
|
|
|
2014-11-23 21:21:17 -06:00
|
|
|
let stack = stack_size.unwrap_or(rt::min_stack());
|
2014-11-14 15:40:34 -06:00
|
|
|
|
|
|
|
// Spawning a new OS thread guarantees that __morestack will never get
|
|
|
|
// triggered, but we must manually set up the actual stack bounds once
|
|
|
|
// this function starts executing. This raises the lower limit by a bit
|
|
|
|
// because by the time that this function is executing we've already
|
|
|
|
// consumed at least a little bit of stack (we don't know the exact byte
|
|
|
|
// address at which our stack started).
|
2014-11-26 09:10:52 -06:00
|
|
|
Thread::spawn_stack(stack, move|| {
|
2014-11-14 15:40:34 -06:00
|
|
|
let something_around_the_top_of_the_stack = 1;
|
|
|
|
let addr = &something_around_the_top_of_the_stack as *const int;
|
|
|
|
let my_stack = addr as uint;
|
|
|
|
unsafe {
|
|
|
|
stack::record_os_managed_stack_bounds(my_stack - stack + 1024,
|
|
|
|
my_stack);
|
|
|
|
}
|
|
|
|
task.stack_guard = thread::current_guard_page();
|
|
|
|
task.stack_bounds = (my_stack - stack + 1024, my_stack);
|
|
|
|
|
|
|
|
let mut f = Some(f);
|
2014-11-26 09:10:52 -06:00
|
|
|
drop(task.run(|| { f.take().unwrap().invoke(()) }).destroy());
|
2014-11-14 15:40:34 -06:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Consumes ownership of a thread, runs some code, and returns the thread back.
|
2013-12-12 20:01:59 -06:00
|
|
|
///
|
2014-06-13 18:03:41 -05:00
|
|
|
/// This function can be used as an emulated "try/catch" to interoperate
|
|
|
|
/// with the rust runtime at the outermost boundary. It is not possible to
|
|
|
|
/// use this function in a nested fashion (a try/catch inside of another
|
2014-07-02 20:27:07 -05:00
|
|
|
/// try/catch). Invoking this function is quite cheap.
|
2014-06-13 18:03:41 -05:00
|
|
|
///
|
2014-12-26 15:04:27 -06:00
|
|
|
/// If the closure `f` succeeds, then the returned thread can be used again
|
2014-10-09 14:17:22 -05:00
|
|
|
/// for another invocation of `run`. If the closure `f` panics then `self`
|
2014-06-13 18:03:41 -05:00
|
|
|
/// will be internally destroyed along with all of the other associated
|
2014-12-26 15:04:27 -06:00
|
|
|
/// resources of this thread. The `on_exit` callback is invoked with the
|
2014-10-09 14:17:22 -05:00
|
|
|
/// cause of panic (not returned here). This can be discovered by querying
|
2014-06-13 18:03:41 -05:00
|
|
|
/// `is_destroyed()`.
|
|
|
|
///
|
|
|
|
/// Note that it is possible to view partial execution of the closure `f`
|
|
|
|
/// because it is not guaranteed to run to completion, but this function is
|
2014-10-09 14:17:22 -05:00
|
|
|
/// guaranteed to return if it panicks. Care should be taken to ensure that
|
2014-06-13 18:03:41 -05:00
|
|
|
/// stack references made by `f` are handled appropriately.
|
|
|
|
///
|
2014-12-26 15:04:27 -06:00
|
|
|
/// It is invalid to call this function with a thread that has been previously
|
2014-06-13 18:03:41 -05:00
|
|
|
/// destroyed via a failed call to `run`.
|
2014-07-24 00:48:04 -05:00
|
|
|
pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> {
|
2014-12-26 15:04:27 -06:00
|
|
|
assert!(!self.is_destroyed(), "cannot re-use a destroyed thread");
|
2014-06-13 18:03:41 -05:00
|
|
|
|
|
|
|
// First, make sure that no one else is in TLS. This does not allow
|
|
|
|
// recursive invocations of run(). If there's no one else, then
|
|
|
|
// relinquish ownership of ourselves back into TLS.
|
|
|
|
if Local::exists(None::<Task>) {
|
2014-12-26 15:04:27 -06:00
|
|
|
panic!("cannot run a thread recursively inside another");
|
2014-06-13 18:03:41 -05:00
|
|
|
}
|
2014-07-24 00:48:04 -05:00
|
|
|
self.state = Armed;
|
2013-12-12 20:01:59 -06:00
|
|
|
Local::put(self);
|
2013-04-22 19:15:31 -05:00
|
|
|
|
2014-06-13 18:03:41 -05:00
|
|
|
// There are two primary reasons that general try/catch is unsafe. The
|
|
|
|
// first is that we do not support nested try/catch. The above check for
|
2014-12-26 15:04:27 -06:00
|
|
|
// an existing thread in TLS is sufficient for this invariant to be
|
2014-06-13 18:03:41 -05:00
|
|
|
// upheld. The second is that unwinding while unwinding is not defined.
|
2014-12-26 15:04:27 -06:00
|
|
|
// We take care of that by having an 'unwinding' flag in the thread
|
2014-06-13 18:03:41 -05:00
|
|
|
// itself. For these reasons, this unsafety should be ok.
|
|
|
|
let result = unsafe { unwind::try(f) };
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
// After running the closure given return the thread back out if it ran
|
|
|
|
// successfully, or clean up the thread if it panicked.
|
2014-06-13 18:03:41 -05:00
|
|
|
let task: Box<Task> = Local::take();
|
|
|
|
match result {
|
|
|
|
Ok(()) => task,
|
|
|
|
Err(cause) => { task.cleanup(Err(cause)) }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Destroy all associated resources of this thread.
|
2014-06-13 18:03:41 -05:00
|
|
|
///
|
2014-12-26 15:04:27 -06:00
|
|
|
/// This function will perform any necessary clean up to prepare the thread
|
2014-06-13 18:03:41 -05:00
|
|
|
/// for destruction. It is required that this is called before a `Task`
|
|
|
|
/// falls out of scope.
|
|
|
|
///
|
2014-12-26 15:04:27 -06:00
|
|
|
/// The returned thread cannot be used for running any more code, but it may
|
2014-06-13 18:03:41 -05:00
|
|
|
/// be used to extract the runtime as necessary.
|
2014-07-23 12:21:50 -05:00
|
|
|
pub fn destroy(self: Box<Task>) -> Box<Task> {
|
2014-06-13 18:03:41 -05:00
|
|
|
if self.is_destroyed() {
|
|
|
|
self
|
|
|
|
} else {
|
|
|
|
self.cleanup(Ok(()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Cleans up a thread, processing the result of the thread as appropriate.
|
2014-06-13 18:03:41 -05:00
|
|
|
///
|
2014-12-26 15:04:27 -06:00
|
|
|
/// This function consumes ownership of the thread, deallocating it once it's
|
2014-06-13 18:03:41 -05:00
|
|
|
/// done being processed. It is assumed that TLD and the local heap have
|
|
|
|
/// already been destroyed and/or annihilated.
|
2014-11-14 16:20:57 -06:00
|
|
|
fn cleanup(mut self: Box<Task>, result: Result) -> Box<Task> {
|
2014-06-13 18:03:41 -05:00
|
|
|
// After taking care of the data above, we need to transmit the result
|
2014-12-26 15:04:27 -06:00
|
|
|
// of this thread.
|
2014-11-14 16:20:57 -06:00
|
|
|
let what_to_do = self.death.on_exit.take();
|
|
|
|
Local::put(self);
|
2013-06-22 03:09:06 -05:00
|
|
|
|
2014-06-13 18:03:41 -05:00
|
|
|
// FIXME: this is running in a seriously constrained context. If this
|
2014-09-30 16:09:46 -05:00
|
|
|
// allocates TLD then it will likely abort the runtime. Similarly,
|
2014-10-09 14:17:22 -05:00
|
|
|
// if this panics, this will also likely abort the runtime.
|
2014-06-13 18:03:41 -05:00
|
|
|
//
|
|
|
|
// This closure is currently limited to a channel send via the
|
2014-12-26 15:04:27 -06:00
|
|
|
// standard library's thread interface, but this needs
|
2014-06-13 18:03:41 -05:00
|
|
|
// reconsideration to whether it's a reasonable thing to let a
|
2014-12-26 15:04:27 -06:00
|
|
|
// thread to do or not.
|
2014-06-13 18:03:41 -05:00
|
|
|
match what_to_do {
|
2014-11-26 09:10:52 -06:00
|
|
|
Some(f) => { f.invoke(result) }
|
2014-06-13 18:03:41 -05:00
|
|
|
None => { drop(result) }
|
2013-12-12 23:38:57 -06:00
|
|
|
}
|
2014-06-13 18:03:41 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
// Now that we're done, we remove the thread from TLS and flag it for
|
2014-06-13 18:03:41 -05:00
|
|
|
// destruction.
|
|
|
|
let mut task: Box<Task> = Local::take();
|
2014-07-24 00:48:04 -05:00
|
|
|
task.state = Destroyed;
|
2014-06-13 18:03:41 -05:00
|
|
|
return task;
|
2013-04-22 14:54:03 -05:00
|
|
|
}
|
2013-06-26 18:41:00 -05:00
|
|
|
|
2014-06-13 18:03:41 -05:00
|
|
|
/// Queries whether this can be destroyed or not.
|
2014-07-24 00:48:04 -05:00
|
|
|
pub fn is_destroyed(&self) -> bool { self.state == Destroyed }
|
2014-06-13 18:03:41 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Deschedules the current thread, invoking `f` `amt` times. It is not
|
2013-12-12 20:01:59 -06:00
|
|
|
/// recommended to use this function directly, but rather communication
|
|
|
|
/// primitives in `std::comm` should be used.
|
2014-11-14 15:40:34 -06:00
|
|
|
//
|
|
|
|
// This function gets a little interesting. There are a few safety and
|
|
|
|
// ownership violations going on here, but this is all done in the name of
|
|
|
|
// shared state. Additionally, all of the violations are protected with a
|
|
|
|
// mutex, so in theory there are no races.
|
|
|
|
//
|
2014-12-26 15:04:27 -06:00
|
|
|
// The first thing we need to do is to get a pointer to the thread's internal
|
|
|
|
// mutex. This address will not be changing (because the thread is allocated
|
|
|
|
// on the heap). We must have this handle separately because the thread will
|
2014-11-14 15:40:34 -06:00
|
|
|
// have its ownership transferred to the given closure. We're guaranteed,
|
|
|
|
// however, that this memory will remain valid because *this* is the current
|
2014-12-26 15:04:27 -06:00
|
|
|
// thread's execution thread.
|
2014-11-14 15:40:34 -06:00
|
|
|
//
|
2014-12-26 15:04:27 -06:00
|
|
|
// The next weird part is where ownership of the thread actually goes. We
|
2014-11-14 15:40:34 -06:00
|
|
|
// relinquish it to the `f` blocking function, but upon returning this
|
2014-12-26 15:04:27 -06:00
|
|
|
// function needs to replace the thread back in TLS. There is no communication
|
|
|
|
// from the wakeup thread back to this thread about the thread pointer, and
|
|
|
|
// there's really no need to. In order to get around this, we cast the thread
|
2014-11-14 15:40:34 -06:00
|
|
|
// to a `uint` which is then used at the end of this function to cast back
|
|
|
|
// to a `Box<Task>` object. Naturally, this looks like it violates
|
|
|
|
// ownership semantics in that there may be two `Box<Task>` objects.
|
|
|
|
//
|
|
|
|
// The fun part is that the wakeup half of this implementation knows to
|
2014-12-26 15:04:27 -06:00
|
|
|
// "forget" the thread on the other end. This means that the awakening half of
|
2014-11-14 15:40:34 -06:00
|
|
|
// things silently relinquishes ownership back to this thread, but not in a
|
2014-12-26 15:04:27 -06:00
|
|
|
// way that the compiler can understand. The thread's memory is always valid
|
|
|
|
// for both threads because these operations are all done inside of a mutex.
|
2014-11-14 15:40:34 -06:00
|
|
|
//
|
|
|
|
// You'll also find that if blocking fails (the `f` function hands the
|
|
|
|
// BlockedTask back to us), we will `mem::forget` the handles. The
|
2014-12-26 15:04:27 -06:00
|
|
|
// reasoning for this is the same logic as above in that the thread silently
|
2014-11-14 15:40:34 -06:00
|
|
|
// transfers ownership via the `uint`, not through normal compiler
|
|
|
|
// semantics.
|
|
|
|
//
|
|
|
|
// On a mildly unrelated note, it should also be pointed out that OS
|
|
|
|
// condition variables are susceptible to spurious wakeups, which we need to
|
|
|
|
// be ready for. In order to accommodate for this fact, we have an extra
|
|
|
|
// `awoken` field which indicates whether we were actually woken up via some
|
|
|
|
// invocation of `reawaken`. This flag is only ever accessed inside the
|
|
|
|
// lock, so there's no need to make it atomic.
|
2014-12-02 13:24:40 -06:00
|
|
|
pub fn deschedule<F>(mut self: Box<Task>, times: uint, mut f: F) where
|
|
|
|
F: FnMut(BlockedTask) -> ::core::result::Result<(), BlockedTask>,
|
|
|
|
{
|
2014-11-14 15:40:34 -06:00
|
|
|
unsafe {
|
|
|
|
let me = &mut *self as *mut Task;
|
|
|
|
let task = BlockedTask::block(self);
|
|
|
|
|
|
|
|
if times == 1 {
|
|
|
|
let guard = (*me).lock.lock();
|
|
|
|
(*me).awoken = false;
|
|
|
|
match f(task) {
|
|
|
|
Ok(()) => {
|
|
|
|
while !(*me).awoken {
|
|
|
|
guard.wait();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(task) => { mem::forget(task.wake()); }
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let iter = task.make_selectable(times);
|
|
|
|
let guard = (*me).lock.lock();
|
|
|
|
(*me).awoken = false;
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
// Apply the given closure to all of the "selectable threads",
|
2014-11-14 15:40:34 -06:00
|
|
|
// bailing on the first one that produces an error. Note that
|
|
|
|
// care must be taken such that when an error is occurred, we
|
2014-12-26 15:04:27 -06:00
|
|
|
// may not own the thread, so we may still have to wait for the
|
|
|
|
// thread to become available. In other words, if thread.wake()
|
2014-11-14 15:40:34 -06:00
|
|
|
// returns `None`, then someone else has ownership and we must
|
|
|
|
// wait for their signal.
|
|
|
|
match iter.map(f).filter_map(|a| a.err()).next() {
|
|
|
|
None => {}
|
|
|
|
Some(task) => {
|
|
|
|
match task.wake() {
|
|
|
|
Some(task) => {
|
|
|
|
mem::forget(task);
|
|
|
|
(*me).awoken = true;
|
|
|
|
}
|
|
|
|
None => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
while !(*me).awoken {
|
|
|
|
guard.wait();
|
|
|
|
}
|
|
|
|
}
|
2014-12-26 15:04:27 -06:00
|
|
|
// put the thread back in TLS, and everything is as it once was.
|
2014-11-14 15:40:34 -06:00
|
|
|
Local::put(mem::transmute(me));
|
|
|
|
}
|
2013-12-12 20:01:59 -06:00
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Wakes up a previously blocked thread. This function can only be
|
|
|
|
/// called on threads that were previously blocked in `deschedule`.
|
2014-11-14 15:40:34 -06:00
|
|
|
//
|
2014-12-26 15:04:27 -06:00
|
|
|
// See the comments on `deschedule` for why the thread is forgotten here, and
|
2014-11-14 15:40:34 -06:00
|
|
|
// why it's valid to do so.
|
2014-07-23 12:21:50 -05:00
|
|
|
pub fn reawaken(mut self: Box<Task>) {
|
2014-11-14 15:40:34 -06:00
|
|
|
unsafe {
|
|
|
|
let me = &mut *self as *mut Task;
|
|
|
|
mem::forget(self);
|
|
|
|
let guard = (*me).lock.lock();
|
|
|
|
(*me).awoken = true;
|
|
|
|
guard.signal();
|
|
|
|
}
|
2013-12-12 20:01:59 -06:00
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Yields control of this thread to another thread. This function will
|
2013-12-12 20:01:59 -06:00
|
|
|
/// eventually return, but possibly not immediately. This is used as an
|
2014-12-26 15:04:27 -06:00
|
|
|
/// opportunity to allow other threads a chance to run.
|
2014-11-14 15:40:34 -06:00
|
|
|
pub fn yield_now() {
|
|
|
|
Thread::yield_now();
|
2013-12-12 20:01:59 -06:00
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Returns the stack bounds for this thread in (lo, hi) format. The stack
|
|
|
|
/// bounds may not be known for all threads, so the return value may be
|
2014-01-04 02:06:13 -06:00
|
|
|
/// `None`.
|
2014-01-06 20:39:55 -06:00
|
|
|
pub fn stack_bounds(&self) -> (uint, uint) {
|
2014-11-14 15:40:34 -06:00
|
|
|
self.stack_bounds
|
2014-01-04 02:06:13 -06:00
|
|
|
}
|
2014-01-16 21:58:42 -06:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Returns the stack guard for this thread, if known.
|
2014-11-14 15:40:34 -06:00
|
|
|
pub fn stack_guard(&self) -> Option<uint> {
|
|
|
|
if self.stack_guard != 0 {
|
|
|
|
Some(self.stack_guard)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2014-01-16 21:58:42 -06:00
|
|
|
}
|
2014-07-24 00:48:04 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Consume this thread, flagging it as a candidate for destruction.
|
2014-07-24 00:48:04 -05:00
|
|
|
///
|
2014-12-26 15:04:27 -06:00
|
|
|
/// This function is required to be invoked to destroy a thread. A thread
|
2014-07-24 00:48:04 -05:00
|
|
|
/// destroyed through a normal drop will abort.
|
|
|
|
pub fn drop(mut self) {
|
|
|
|
self.state = Destroyed;
|
|
|
|
}
|
2013-04-22 14:54:03 -05:00
|
|
|
}
|
|
|
|
|
2013-05-19 03:04:01 -05:00
|
|
|
impl Drop for Task {
|
2013-09-16 20:18:07 -05:00
|
|
|
fn drop(&mut self) {
|
2014-12-26 15:04:27 -06:00
|
|
|
rtdebug!("called drop for a thread: {}", self as *mut Task as uint);
|
2014-07-24 00:48:04 -05:00
|
|
|
rtassert!(self.state != Armed);
|
2013-07-19 16:25:05 -05:00
|
|
|
}
|
2013-04-21 18:28:17 -05:00
|
|
|
}
|
|
|
|
|
std: Extract librustrt out of libstd
As part of the libstd facade efforts, this commit extracts the runtime interface
out of the standard library into a standalone crate, librustrt. This crate will
provide the following services:
* Definition of the rtio interface
* Definition of the Runtime interface
* Implementation of the Task structure
* Implementation of task-local-data
* Implementation of task failure via unwinding via libunwind
* Implementation of runtime initialization and shutdown
* Implementation of thread-local-storage for the local rust Task
Notably, this crate avoids the following services:
* Thread creation and destruction. The crate does not require the knowledge of
an OS threading system, and as a result it seemed best to leave out the
`rt::thread` module from librustrt. The librustrt module does depend on
mutexes, however.
* Implementation of backtraces. There is no inherent requirement for the runtime
to be able to generate backtraces. As will be discussed later, this
functionality continues to live in libstd rather than librustrt.
As usual, a number of architectural changes were required to make this crate
possible. Users of "stable" functionality will not be impacted by this change,
but users of the `std::rt` module will likely note the changes. A list of
architectural changes made is:
* The stdout/stderr handles no longer live directly inside of the `Task`
structure. This is a consequence of librustrt not knowing about `std::io`.
These two handles are now stored inside of task-local-data.
The handles were originally stored inside of the `Task` for perf reasons, and
TLD is not currently as fast as it could be. For comparison, 100k prints goes
from 59ms to 68ms (a 15% slowdown). This appeared to me to be an acceptable
perf loss for the successful extraction of a librustrt crate.
* The `rtio` module was forced to duplicate more functionality of `std::io`. As
the module no longer depends on `std::io`, `rtio` now defines structures such
as socket addresses, addrinfo fiddly bits, etc. The primary change made was
that `rtio` now defines its own `IoError` type. This type is distinct from
`std::io::IoError` in that it does not have an enum for what error occurred,
but rather a platform-specific error code.
The native and green libraries will be updated in later commits for this
change, and the bulk of this effort was put behind updating the two libraries
for this change (with `rtio`).
* Printing a message on task failure (along with the backtrace) continues to
live in libstd, not in librustrt. This is a consequence of the above decision
to move the stdout/stderr handles to TLD rather than inside the `Task` itself.
The unwinding API now supports registration of global callback functions which
will be invoked when a task fails, allowing for libstd to register a function
to print a message and a backtrace.
The API for registering a callback is experimental and unsafe, as the
ramifications of running code on unwinding is pretty hairy.
* The `std::unstable::mutex` module has moved to `std::rt::mutex`.
* The `std::unstable::sync` module has been moved to `std::rt::exclusive` and
the type has been rewritten to not internally have an Arc and to have an RAII
guard structure when locking. Old code should stop using `Exclusive` in favor
of the primitives in `libsync`, but if necessary, old code should port to
`Arc<Exclusive<T>>`.
* The local heap has been stripped down to have fewer debugging options. None of
these were tested, and none of these have been used in a very long time.
[breaking-change]
2014-06-03 21:11:49 -05:00
|
|
|
impl TaskOpts {
|
|
|
|
pub fn new() -> TaskOpts {
|
|
|
|
TaskOpts { on_exit: None, name: None, stack_size: None }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-14 21:32:24 -06:00
|
|
|
impl Iterator<BlockedTask> for BlockedTasks {
|
2013-12-12 20:01:59 -06:00
|
|
|
fn next(&mut self) -> Option<BlockedTask> {
|
|
|
|
Some(Shared(self.inner.clone()))
|
2013-06-26 18:41:00 -05:00
|
|
|
}
|
2013-12-12 20:01:59 -06:00
|
|
|
}
|
2013-06-26 18:41:00 -05:00
|
|
|
|
2013-12-12 20:01:59 -06:00
|
|
|
impl BlockedTask {
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Returns Some if the thread was successfully woken; None if already killed.
|
2014-05-05 20:56:44 -05:00
|
|
|
pub fn wake(self) -> Option<Box<Task>> {
|
2013-12-12 20:01:59 -06:00
|
|
|
match self {
|
|
|
|
Owned(task) => Some(task),
|
2014-05-19 19:33:40 -05:00
|
|
|
Shared(arc) => {
|
|
|
|
match arc.swap(0, SeqCst) {
|
2013-12-12 20:01:59 -06:00
|
|
|
0 => None,
|
2014-05-19 19:33:40 -05:00
|
|
|
n => Some(unsafe { mem::transmute(n) }),
|
2013-12-12 20:01:59 -06:00
|
|
|
}
|
|
|
|
}
|
2013-07-19 16:25:05 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Reawakens this thread if ownership is acquired. If finer-grained control
|
2014-04-25 22:47:49 -05:00
|
|
|
/// is desired, use `wake` instead.
|
|
|
|
pub fn reawaken(self) {
|
|
|
|
self.wake().map(|t| t.reawaken());
|
|
|
|
}
|
|
|
|
|
2013-12-12 20:01:59 -06:00
|
|
|
// This assertion has two flavours because the wake involves an atomic op.
|
2014-10-09 14:17:22 -05:00
|
|
|
// In the faster version, destructors will panic dramatically instead.
|
2013-12-12 20:01:59 -06:00
|
|
|
#[cfg(not(test))] pub fn trash(self) { }
|
|
|
|
#[cfg(test)] pub fn trash(self) { assert!(self.wake().is_none()); }
|
2013-06-26 18:41:00 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Create a blocked thread, unless the thread was already killed.
|
2014-05-05 20:56:44 -05:00
|
|
|
pub fn block(task: Box<Task>) -> BlockedTask {
|
2013-12-12 20:01:59 -06:00
|
|
|
Owned(task)
|
|
|
|
}
|
2013-07-19 16:25:05 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
/// Converts one blocked thread handle to a list of many handles to the same.
|
2014-04-13 16:39:04 -05:00
|
|
|
pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> {
|
2013-12-12 20:01:59 -06:00
|
|
|
let arc = match self {
|
|
|
|
Owned(task) => {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
let flag = unsafe { AtomicUint::new(mem::transmute(task)) };
|
2014-05-19 19:33:40 -05:00
|
|
|
Arc::new(flag)
|
2013-06-26 18:41:00 -05:00
|
|
|
}
|
2013-12-12 20:01:59 -06:00
|
|
|
Shared(arc) => arc.clone(),
|
2013-06-26 18:41:00 -05:00
|
|
|
};
|
2014-01-14 21:32:24 -06:00
|
|
|
BlockedTasks{ inner: arc }.take(num_handles)
|
2013-06-26 18:41:00 -05:00
|
|
|
}
|
|
|
|
|
2013-12-12 20:01:59 -06:00
|
|
|
/// Convert to an unsafe uint value. Useful for storing in a pipe's state
|
|
|
|
/// flag.
|
|
|
|
#[inline]
|
|
|
|
pub unsafe fn cast_to_uint(self) -> uint {
|
2013-06-26 18:41:00 -05:00
|
|
|
match self {
|
2013-12-12 20:01:59 -06:00
|
|
|
Owned(task) => {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
let blocked_task_ptr: uint = mem::transmute(task);
|
2013-12-12 20:01:59 -06:00
|
|
|
rtassert!(blocked_task_ptr & 0x1 == 0);
|
|
|
|
blocked_task_ptr
|
|
|
|
}
|
|
|
|
Shared(arc) => {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
let blocked_task_ptr: uint = mem::transmute(box arc);
|
2013-12-12 20:01:59 -06:00
|
|
|
rtassert!(blocked_task_ptr & 0x1 == 0);
|
|
|
|
blocked_task_ptr | 0x1
|
2013-06-26 18:41:00 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-12-12 20:01:59 -06:00
|
|
|
/// Convert from an unsafe uint value. Useful for retrieving a pipe's state
|
|
|
|
/// flag.
|
|
|
|
#[inline]
|
|
|
|
pub unsafe fn cast_from_uint(blocked_task_ptr: uint) -> BlockedTask {
|
|
|
|
if blocked_task_ptr & 0x1 == 0 {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
Owned(mem::transmute(blocked_task_ptr))
|
2013-10-17 03:40:33 -05:00
|
|
|
} else {
|
2014-05-19 19:33:40 -05:00
|
|
|
let ptr: Box<Arc<AtomicUint>> =
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
mem::transmute(blocked_task_ptr & !1);
|
2013-12-12 20:01:59 -06:00
|
|
|
Shared(*ptr)
|
2013-10-17 03:40:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-12-12 20:01:59 -06:00
|
|
|
impl Death {
|
|
|
|
pub fn new() -> Death {
|
2014-12-13 22:06:44 -06:00
|
|
|
Death { on_exit: None }
|
2013-10-09 12:34:27 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-04-21 21:03:52 -05:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
2013-10-27 14:12:40 -05:00
|
|
|
use super::*;
|
2014-11-23 21:21:17 -06:00
|
|
|
use prelude::*;
|
|
|
|
use task;
|
|
|
|
use rt::unwind;
|
2013-04-22 14:54:03 -05:00
|
|
|
|
2013-04-22 19:15:31 -05:00
|
|
|
#[test]
|
|
|
|
fn unwind() {
|
2014-11-26 09:10:52 -06:00
|
|
|
let result = task::try(move|| ());
|
2013-12-12 23:38:57 -06:00
|
|
|
rtdebug!("trying first assert");
|
|
|
|
assert!(result.is_ok());
|
2014-11-26 09:10:52 -06:00
|
|
|
let result = task::try(move|| -> () panic!());
|
2013-12-12 23:38:57 -06:00
|
|
|
rtdebug!("trying second assert");
|
|
|
|
assert!(result.is_err());
|
2013-04-22 19:15:31 -05:00
|
|
|
}
|
2013-05-06 20:24:37 -05:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn rng() {
|
2014-11-23 21:21:17 -06:00
|
|
|
use rand::{StdRng, Rng};
|
2014-05-01 13:12:16 -05:00
|
|
|
let mut r = StdRng::new().ok().unwrap();
|
2013-12-12 23:38:57 -06:00
|
|
|
let _ = r.next_u32();
|
2013-05-06 20:24:37 -05:00
|
|
|
}
|
2013-04-27 20:57:15 -05:00
|
|
|
|
2013-05-17 01:12:22 -05:00
|
|
|
#[test]
|
|
|
|
fn comm_stream() {
|
2014-03-09 16:58:32 -05:00
|
|
|
let (tx, rx) = channel();
|
2014-06-27 14:30:25 -05:00
|
|
|
tx.send(10i);
|
2014-03-09 16:58:32 -05:00
|
|
|
assert!(rx.recv() == 10);
|
2013-05-17 01:12:22 -05:00
|
|
|
}
|
2013-06-14 01:31:19 -05:00
|
|
|
|
2013-06-20 20:26:56 -05:00
|
|
|
#[test]
|
|
|
|
fn comm_shared_chan() {
|
2014-03-09 16:58:32 -05:00
|
|
|
let (tx, rx) = channel();
|
2014-06-27 14:30:25 -05:00
|
|
|
tx.send(10i);
|
2014-03-09 16:58:32 -05:00
|
|
|
assert!(rx.recv() == 10);
|
2013-06-20 20:26:56 -05:00
|
|
|
}
|
|
|
|
|
2013-10-27 14:12:40 -05:00
|
|
|
#[test]
|
|
|
|
#[should_fail]
|
2013-12-18 11:57:58 -06:00
|
|
|
fn test_begin_unwind() {
|
2014-11-23 21:21:17 -06:00
|
|
|
use rt::unwind::begin_unwind;
|
2014-07-31 10:13:25 -05:00
|
|
|
begin_unwind("cause", &(file!(), line!()))
|
2013-12-18 11:57:58 -06:00
|
|
|
}
|
2013-12-12 20:01:59 -06:00
|
|
|
|
2014-07-24 00:48:04 -05:00
|
|
|
#[test]
|
|
|
|
fn drop_new_task_ok() {
|
2014-11-15 01:05:37 -06:00
|
|
|
drop(Task::new(None, None));
|
2014-07-24 00:48:04 -05:00
|
|
|
}
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
// Thread blocking tests
|
2013-12-12 20:01:59 -06:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn block_and_wake() {
|
2014-11-15 01:05:37 -06:00
|
|
|
let task = box Task::new(None, None);
|
2014-09-09 04:32:58 -05:00
|
|
|
let task = BlockedTask::block(task).wake().unwrap();
|
2014-07-24 09:32:14 -05:00
|
|
|
task.drop();
|
2013-12-12 20:01:59 -06:00
|
|
|
}
|
2013-05-08 14:26:34 -05:00
|
|
|
}
|