Task management.
An executing Rust program consists of a tree of tasks, each with their own stack, and sole ownership of their allocated heap data. Tasks communicate with each other using ports and channels.
When a task fails, that failure will propagate to its parent (the task that spawned it) and the parent will fail as well. The reverse is not true: when a parent task fails its children will continue executing. When the root (main) task fails, all tasks fail, and then so does the entire process.
Tasks may execute in parallel and are scheduled automatically by the runtime.
do spawn {
log(error, "Hello, World!");
}
local_data_key
sched_opts
- Scheduler configuration optionstask_opts
- Task configuration optionsbuilder
- The task builder type.notification
- A message type for notifying of task lifecycle eventssched_mode
- Scheduler modestask
- A handle to a tasktask_result
- Indicates the manner in which a task exited.extensions of iter::base_iter<A> for IMPL_T<A>
extensions for IMPL_T<A>
extensions for *T
- Extension methods for pointersextensions for dvec<A>
extensions for dvec<A>
extensions of iter::base_iter<A> for IMPL_T<A>
extensions for IMPL_T<A>
add_wrapper
- Add a wrapper to the body of the spawned task.builder
- Construct a builderdefault_task_opts
- The default task optionsfailing
- True if the running task has failedfuture_result
- Get a future representing the exit status of the task.future_task
- Get a future representing the handle to the new taskget_opts
- Get the task_opts associated with a builderget_task
- Get a handle to the running tasklocal_data_get
- Retrieve a task-local data valuelocal_data_modify
- Modify a task-local data valuelocal_data_pop
- Remove a task-local data value from the table, returning the reference that was originally created to insert it.local_data_set
- Store a value in task-local datarun
- Creates and exucutes a new child taskrun_listener
- Runs a new task while providing a channel from the parent to the childset_opts
- Set the task_opts associated with a builderset_sched_mode
spawn
- Creates and executes a new child taskspawn_listener
- Runs a new task while providing a channel from the parent to the childspawn_sched
- Creates a new scheduler and executes a task on itspawn_with
- Runs a task, while transfering ownership of one argument to the child.try
- Execute a function in another task and return either the return value of the function or result::err.unkillable
- Temporarily make the task unkillableunsupervise
- Configures the new task to not propagate failure to its parentyield
- Yield control to the task schedulerlocal_data_key
type local_data_key<T> = fn@(+@T)
sched_opts
type sched_opts = {mode: sched_mode, foreign_stack_size: option<uint>,}
Scheduler configuration options
sched_mode - The operating mode of the scheduler
foreign_stack_size - The size of the foreign stack, in bytes
Rust code runs on Rust-specific stacks. When Rust code calls foreign code (via functions in foreign modules) it switches to a typical, large stack appropriate for running code written in languages like C. By default these foreign stacks have unspecified size, but with this option their size can be precisely specified.
task_opts
type task_opts = {supervise: bool,
notify_chan: option<comm::chan<notification>>,
sched: option<sched_opts>,}
Task configuration options
supervise - Do not propagate failure to the parent task
All tasks are linked together via a tree, from parents to children. By default children are 'supervised' by their parent and when they fail so too will their parents. Settings this flag to false disables that behavior.
notify_chan - Enable lifecycle notifications on the given channel
sched - Specify the configuration of a new scheduler to create the task in
By default, every task is created in the same scheduler as its parent, where it is scheduled cooperatively with all other tasks in that scheduler. Some specialized applications may want more control over their scheduling, in which case they can be spawned into a new scheduler with the specific properties required.
This is of particular importance for libraries which want to call into foreign code that blocks. Without doing so in a different scheduler other tasks will be impeded or even blocked indefinitely.
builder
The task builder type.
Provides detailed control over the properties and behavior of new tasks.
builder_({mut opts: task_opts, mut gen_body: fn@(+fn~()) -> fn~(), can_not_copy: option<comm::port<()>>,})
notification
A message type for notifying of task lifecycle events
exit(task, task_result)
- Sent when a task exits with the task handle and resultsched_mode
Scheduler modes
single_threaded
- All tasks run in the same OS threadthread_per_core
- Tasks are distributed among available CPUsthread_per_task
- Each task runs in its own OS threadmanual_threads(uint)
- Tasks are distributed among a fixed number of OS threadsosmain
- Tasks are scheduled on the main OS threadThe main OS thread is the thread used to launch the runtime which, in most cases, is the process's initial thread as created by the OS.
task
A handle to a task
task(task_id)
task_result
Indicates the manner in which a task exited.
A task that completes without failing and whose supervised children complete without failing is considered to exit successfully.
FIXME (See #1868): This description does not indicate the current behavior for linked failure.
success
failure
extensions of iter::base_iter<A> for IMPL_T<A>
each
fn each(blk: fn(A) -> bool)
size_hint
fn size_hint() -> option<uint>
eachi
fn eachi(blk: fn(uint, A) -> bool)
all
fn all(blk: fn(A) -> bool) -> bool
any
fn any(blk: fn(A) -> bool) -> bool
foldl
fn foldl<B>(+b0: B, blk: fn(B, A) -> B) -> B
contains
fn contains(x: A) -> bool
count
fn count(x: A) -> uint
position
fn position(f: fn(A) -> bool) -> option<uint>
extensions for IMPL_T<A>
filter_to_vec
fn filter_to_vec(pred: fn(A) -> bool) -> ~[A]
map_to_vec
fn map_to_vec<B>(op: fn(A) -> B) -> ~[B]
to_vec
fn to_vec() -> ~[A]
min
fn min() -> A
max
fn max() -> A
find
fn find(p: fn(A) -> bool) -> option<A>
extensions for *T
Extension methods for pointers
is_null
pure fn is_null() -> bool
Returns true if the pointer is equal to the null pointer.
is_not_null
pure fn is_not_null() -> bool
Returns true if the pointer is not equal to the null pointer.
extensions for dvec<A>
swap
fn swap(f: fn(-~[mut A]) -> ~[mut A])
Swaps out the current vector and hands it off to a user-provided function f
. The function should transform it however is desired and return a new vector to replace it with.
len
fn len() -> uint
Returns the number of elements currently in the dvec
set
fn set(+w: ~[mut A])
Overwrite the current contents
pop
fn pop() -> A
Remove and return the last element
unshift
fn unshift(-t: A)
Insert a single item at the front of the list
push
fn push(+t: A)
Append a single item to the end of the list
shift
fn shift() -> A
Remove and return the first element
extensions for dvec<A>
push_all
fn push_all(ts: & [const A])
Append all elements of a vector to the end of the list
Equivalent to append_iter()
but potentially more efficient.
push_slice
fn push_slice(ts: & [const A], from_idx: uint, to_idx: uint)
Appends elements from from_idx
to to_idx
(exclusive)
get
fn get() -> ~[A]
Gets a copy of the current contents.
See unwrap()
if you do not wish to copy the contents.
[]
fn [](idx: uint) -> A
Copy out an individual element
get_elt
fn get_elt(idx: uint) -> A
Copy out an individual element
set_elt
fn set_elt(idx: uint, a: A)
Overwrites the contents of the element at idx
with a
grow_set_elt
fn grow_set_elt(idx: uint, initval: A, val: A)
Overwrites the contents of the element at idx
with a
, growing the vector if necessary. New elements will be initialized with initval
last
fn last() -> A
Returns the last element, failing if the vector is empty
reach
fn reach(f: fn(A) -> bool)
Iterates over the elements in reverse order
extensions of iter::base_iter<A> for IMPL_T<A>
each
fn each(blk: fn(A) -> bool)
size_hint
fn size_hint() -> option<uint>
eachi
fn eachi(blk: fn(uint, A) -> bool)
all
fn all(blk: fn(A) -> bool) -> bool
any
fn any(blk: fn(A) -> bool) -> bool
foldl
fn foldl<B>(+b0: B, blk: fn(B, A) -> B) -> B
contains
fn contains(x: A) -> bool
count
fn count(x: A) -> uint
position
fn position(f: fn(A) -> bool) -> option<uint>
extensions for IMPL_T<A>
filter_to_vec
fn filter_to_vec(pred: fn(A) -> bool) -> ~[A]
map_to_vec
fn map_to_vec<B>(op: fn(A) -> B) -> ~[B]
to_vec
fn to_vec() -> ~[A]
min
fn min() -> A
max
fn max() -> A
find
fn find(p: fn(A) -> bool) -> option<A>
add_wrapper
fn add_wrapper(builder: builder, gen_body: fn@(+fn~()) -> fn~())
Add a wrapper to the body of the spawned task.
Before the task is spawned it is passed through a 'body generator' function that may perform local setup operations as well as wrap the task body in remote setup operations. With this the behavior of tasks can be extended in simple ways.
This function augments the current body generator with a new body generator by applying the task body which results from the existing body generator to the new body generator.
builder
fn builder() -> builder
Construct a builder
default_task_opts
fn default_task_opts() -> task_opts
The default task options
By default all tasks are supervised by their parent, are spawned into the same scheduler, and do not post lifecycle notifications.
failing
fn failing() -> bool
True if the running task has failed
future_result
fn future_result(builder: builder) -> future::future<task_result>
Get a future representing the exit status of the task.
Taking the value of the future will block until the child task terminates.
Note that the future returning by this function is only useful for obtaining the value of the next task to be spawning with the builder. If additional tasks are spawned with the same builder then a new result future must be obtained prior to spawning each task.
future_task
fn future_task(builder: builder) -> future::future<task>
Get a future representing the handle to the new task
get_opts
fn get_opts(builder: builder) -> task_opts
Get the task_opts associated with a builder
get_task
fn get_task() -> task
Get a handle to the running task
local_data_get
unsafe fn local_data_get<T>(key: local_data_key<T>) -> option<@T>
Retrieve a task-local data value. It will also be kept alive in the table until explicitly removed.
local_data_modify
unsafe fn local_data_modify<T>(key: local_data_key<T>,
modify_fn: fn(option<@T>) -> option<@T>)
Modify a task-local data value. If the function returns 'none', the data is removed (and its reference dropped).
local_data_pop
unsafe fn local_data_pop<T>(key: local_data_key<T>) -> option<@T>
Remove a task-local data value from the table, returning the reference that was originally created to insert it.
local_data_set
unsafe fn local_data_set<T>(key: local_data_key<T>, -data: @T)
Store a value in task-local data. If this key already has a value, that value is overwritten (and its destructor is run).
run
fn run(-builder: builder, +f: fn~())
Creates and exucutes a new child task
Sets up a new task with its own call stack and schedules it to run the provided unique closure. The task has the properties and behavior specified by builder
.
When spawning into a new scheduler, the number of threads requested must be greater than zero.
run_listener
fn run_listener<A: send>(-builder: builder, +f: fn~(comm::port<A>)) ->
comm::chan<A>
Runs a new task while providing a channel from the parent to the child
Sets up a communication channel from the current task to the new child task, passes the port to child's body, and returns a channel linked to the port to the parent.
This encapsulates some boilerplate handshaking logic that would otherwise be required to establish communication from the parent to the child.
set_opts
fn set_opts(builder: builder, opts: task_opts)
Set the task_opts associated with a builder
To update a single option use a pattern like the following:
set_opts(builder, {
supervise: false
with get_opts(builder)
});
set_sched_mode
fn set_sched_mode(builder: builder, mode: sched_mode)
spawn
fn spawn(+f: fn~())
Creates and executes a new child task
Sets up a new task with its own call stack and schedules it to run the provided unique closure.
This function is equivalent to run(new_builder(), f)
.
spawn_listener
fn spawn_listener<A: send>(+f: fn~(comm::port<A>)) -> comm::chan<A>
Runs a new task while providing a channel from the parent to the child
Sets up a communication channel from the current task to the new child task, passes the port to child's body, and returns a channel linked to the port to the parent.
This encapsulates some boilerplate handshaking logic that would otherwise be required to establish communication from the parent to the child.
The simplest way to establish bidirectional communication between a parent in child is as follows:
let po = comm::port();
let ch = comm::chan(po);
let ch = do spawn_listener |po| {
// Now the child has a port called 'po' to read from and
// an environment-captured channel called 'ch'.
};
// Likewise, the parent has both a 'po' and 'ch'
This function is equivalent to run_listener(builder(), f)
.
spawn_sched
fn spawn_sched(mode: sched_mode, +f: fn~())
Creates a new scheduler and executes a task on it
Tasks subsequently spawned by that task will also execute on the new scheduler. When there are no more tasks to execute the scheduler terminates.
In manual threads mode the number of threads requested must be greater than zero.
spawn_with
fn spawn_with<A: send>(+arg: A, +f: fn~(+A))
Runs a task, while transfering ownership of one argument to the child.
This is useful for transfering ownership of noncopyables to another task.
This function is equivalent to run_with(builder(), arg, f)
.
try
fn try<T: send>(+f: fn~() -> T) -> result<T, ()>
Execute a function in another task and return either the return value of the function or result::err.
If the function executed successfully then try returns result::ok containing the value returned by the function. If the function fails then try returns result::err containing nil.
unkillable
unsafe fn unkillable(f: fn())
Temporarily make the task unkillable
do task::unkillable {
// detach / yield / destroy must all be called together
rustrt::rust_port_detach(po);
// This must not result in the current task being killed
task::yield();
rustrt::rust_port_destroy(po);
}
unsupervise
fn unsupervise(builder: builder)
Configures the new task to not propagate failure to its parent
yield
fn yield()
Yield control to the task scheduler