Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

s/task/thread/g #20248

Merged
merged 1 commit into from
Dec 30, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 56 additions & 56 deletions src/doc/guide-tasks.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
% The Rust Tasks and Communication Guide
% The Rust Threads and Communication Guide

**NOTE** This guide is badly out of date an needs to be rewritten.
**NOTE** This guide is badly out of date and needs to be rewritten.

# Introduction

Expand All @@ -9,36 +9,36 @@ primitives. This guide will describe the concurrency model in Rust, how it
relates to the Rust type system, and introduce the fundamental library
abstractions for constructing concurrent programs.

Tasks provide failure isolation and recovery. When a fatal error occurs in Rust
Threads provide failure isolation and recovery. When a fatal error occurs in Rust
code as a result of an explicit call to `panic!()`, an assertion failure, or
another invalid operation, the runtime system destroys the entire task. Unlike
another invalid operation, the runtime system destroys the entire thread. Unlike
in languages such as Java and C++, there is no way to `catch` an exception.
Instead, tasks may monitor each other to see if they panic.
Instead, threads may monitor each other to see if they panic.

Tasks use Rust's type system to provide strong memory safety guarantees. In
particular, the type system guarantees that tasks cannot induce a data race
Threads use Rust's type system to provide strong memory safety guarantees. In
particular, the type system guarantees that threads cannot induce a data race
from shared mutable state.

# Basics

At its simplest, creating a task is a matter of calling the `spawn` function
with a closure argument. `spawn` executes the closure in the new task.
At its simplest, creating a thread is a matter of calling the `spawn` function
with a closure argument. `spawn` executes the closure in the new thread.

```{rust,ignore}
# use std::task::spawn;
# use std::thread::spawn;

// Print something profound in a different task using a named function
fn print_message() { println!("I am running in a different task!"); }
// Print something profound in a different thread using a named function
fn print_message() { println!("I am running in a different thread!"); }
spawn(print_message);

// Alternatively, use a `move ||` expression instead of a named function.
// `||` expressions evaluate to an unnamed closure. The `move` keyword
// indicates that the closure should take ownership of any variables it
// touches.
spawn(move || println!("I am also running in a different task!"));
spawn(move || println!("I am also running in a different thread!"));
```

In Rust, a task is not a concept that appears in the language semantics.
In Rust, a thread is not a concept that appears in the language semantics.
Instead, Rust's type system provides all the tools necessary to implement safe
concurrency: particularly, ownership. The language leaves the implementation
details to the standard library.
Expand All @@ -49,26 +49,26 @@ argument a closure (of type `F`) that it will run exactly once. This
closure is limited to capturing `Send`-able data from its environment
(that is, data which is deeply owned). Limiting the closure to `Send`
ensures that `spawn` can safely move the entire closure and all its
associated state into an entirely different task for execution.
associated state into an entirely different thread for execution.

```{rust,ignore}
# use std::task::spawn;
# fn generate_task_number() -> int { 0 }
# use std::thread::spawn;
# fn generate_thread_number() -> int { 0 }
// Generate some state locally
let child_task_number = generate_task_number();
let child_thread_number = generate_thread_number();

spawn(move || {
// Capture it in the remote task. The `move` keyword indicates
// that this closure should move `child_task_number` into its
// Capture it in the remote thread. The `move` keyword indicates
// that this closure should move `child_thread_number` into its
// environment, rather than capturing a reference into the
// enclosing stack frame.
println!("I am child number {}", child_task_number);
println!("I am child number {}", child_thread_number);
});
```

## Communication

Now that we have spawned a new task, it would be nice if we could communicate
Now that we have spawned a new thread, it would be nice if we could communicate
with it. For this, we use *channels*. A channel is simply a pair of endpoints:
one for sending messages and another for receiving messages.

Expand All @@ -78,7 +78,7 @@ of a channel, and a **receiver** is the receiving endpoint. Consider the followi
example of calculating two results concurrently:

```{rust,ignore}
# use std::task::spawn;
# use std::thread::spawn;

let (tx, rx): (Sender<int>, Receiver<int>) = channel();

Expand All @@ -102,12 +102,12 @@ into its component parts).
let (tx, rx): (Sender<int>, Receiver<int>) = channel();
```

The child task will use the sender to send data to the parent task, which will
The child thread will use the sender to send data to the parent thread, which will
wait to receive the data on the receiver. The next statement spawns the child
task.
thread.

```{rust,ignore}
# use std::task::spawn;
# use std::thread::spawn;
# fn some_expensive_computation() -> int { 42 }
# let (tx, rx) = channel();
spawn(move || {
Expand All @@ -116,10 +116,10 @@ spawn(move || {
});
```

Notice that the creation of the task closure transfers `tx` to the child task
Notice that the creation of the thread closure transfers `tx` to the child thread
implicitly: the closure captures `tx` in its environment. Both `Sender` and
`Receiver` are sendable types and may be captured into tasks or otherwise
transferred between them. In the example, the child task runs an expensive
`Receiver` are sendable types and may be captured into threads or otherwise
transferred between them. In the example, the child thread runs an expensive
computation, then sends the result over the captured channel.

Finally, the parent continues with some other expensive computation, then waits
Expand All @@ -137,7 +137,7 @@ The `Sender` and `Receiver` pair created by `channel` enables efficient
communication between a single sender and a single receiver, but multiple
senders cannot use a single `Sender` value, and multiple receivers cannot use a
single `Receiver` value. What if our example needed to compute multiple
results across a number of tasks? The following program is ill-typed:
results across a number of threads? The following program is ill-typed:

```{rust,ignore}
# fn some_expensive_computation() -> int { 42 }
Expand All @@ -160,7 +160,7 @@ Instead we can clone the `tx`, which allows for multiple senders.
let (tx, rx) = channel();

for init_val in range(0u, 3) {
// Create a new channel handle to distribute to the child task
// Create a new channel handle to distribute to the child thread
let child_tx = tx.clone();
spawn(move || {
child_tx.send(some_expensive_computation(init_val));
Expand All @@ -172,7 +172,7 @@ let result = rx.recv() + rx.recv() + rx.recv();
```

Cloning a `Sender` produces a new handle to the same channel, allowing multiple
tasks to send data to a single receiver. It upgrades the channel internally in
threads to send data to a single receiver. It upgrades the channel internally in
order to allow this functionality, which means that channels that are not
cloned can avoid the overhead required to handle multiple senders. But this
fact has no bearing on the channel's usage: the upgrade is transparent.
Expand All @@ -182,9 +182,9 @@ simply use three `Sender` pairs, but it serves to illustrate the point. For
reference, written with multiple streams, it might look like the example below.

```{rust,ignore}
# use std::task::spawn;
# use std::thread::spawn;

// Create a vector of ports, one for each child task
// Create a vector of ports, one for each child thread
let rxs = Vec::from_fn(3, |init_val| {
let (tx, rx) = channel();
spawn(move || {
Expand Down Expand Up @@ -256,18 +256,18 @@ fn main() {

## Sharing without copying: Arc

To share data between tasks, a first approach would be to only use channel as
To share data between threads, a first approach would be to only use channel as
we have seen previously. A copy of the data to share would then be made for
each task. In some cases, this would add up to a significant amount of wasted
each thread. In some cases, this would add up to a significant amount of wasted
memory and would require copying the same data more than necessary.

To tackle this issue, one can use an Atomically Reference Counted wrapper
(`Arc`) as implemented in the `sync` library of Rust. With an Arc, the data
will no longer be copied for each task. The Arc acts as a reference to the
will no longer be copied for each thread. The Arc acts as a reference to the
shared data and only this reference is shared and cloned.

Here is a small example showing how to use Arcs. We wish to run concurrently
several computations on a single large vector of floats. Each task needs the
several computations on a single large vector of floats. Each thread needs the
full vector to perform its duty.

```{rust,ignore}
Expand All @@ -284,10 +284,10 @@ fn main() {
let numbers_arc = Arc::new(numbers);

for num in range(1u, 10) {
let task_numbers = numbers_arc.clone();
let thread_numbers = numbers_arc.clone();

spawn(move || {
println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
});
}
}
Expand All @@ -306,8 +306,8 @@ let numbers_arc = Arc::new(numbers);
# }
```

and a clone is captured for each task via a procedure. This only copies
the wrapper and not its contents. Within the task's procedure, the captured
and a clone is captured for each thread via a procedure. This only copies
the wrapper and not its contents. Within the thread's procedure, the captured
Arc reference can be used as a shared reference to the underlying vector as
if it were local.

Expand All @@ -319,29 +319,29 @@ if it were local.
# let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
# let numbers_arc = Arc::new(numbers);
# let num = 4;
let task_numbers = numbers_arc.clone();
let thread_numbers = numbers_arc.clone();
spawn(move || {
// Capture task_numbers and use it as if it was the underlying vector
println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
// Capture thread_numbers and use it as if it was the underlying vector
println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
});
# }
```

# Handling task panics
# Handling thread panics

Rust has a built-in mechanism for raising exceptions. The `panic!()` macro
(which can also be written with an error string as an argument: `panic!(
~reason)`) and the `assert!` construct (which effectively calls `panic!()` if a
boolean expression is false) are both ways to raise exceptions. When a task
raises an exception, the task unwinds its stack—running destructors and
boolean expression is false) are both ways to raise exceptions. When a thread
raises an exception, the thread unwinds its stack—running destructors and
freeing memory along the way—and then exits. Unlike exceptions in C++,
exceptions in Rust are unrecoverable within a single task: once a task panics,
exceptions in Rust are unrecoverable within a single thread: once a thread panics,
there is no way to "catch" the exception.

While it isn't possible for a task to recover from panicking, tasks may notify
While it isn't possible for a thread to recover from panicking, threads may notify
each other if they panic. The simplest way of handling a panic is with the
`try` function, which is similar to `spawn`, but immediately blocks and waits
for the child task to finish. `try` returns a value of type
for the child thread to finish. `try` returns a value of type
`Result<T, Box<Any + Send>>`. `Result` is an `enum` type with two variants:
`Ok` and `Err`. In this case, because the type arguments to `Result` are `int`
and `()`, callers can pattern-match on a result to check whether it's an `Ok`
Expand All @@ -364,19 +364,19 @@ assert!(result.is_err());

Unlike `spawn`, the function spawned using `try` may return a value, which
`try` will dutifully propagate back to the caller in a [`Result`] enum. If the
child task terminates successfully, `try` will return an `Ok` result; if the
child task panics, `try` will return an `Error` result.
child thread terminates successfully, `try` will return an `Ok` result; if the
child thread panics, `try` will return an `Error` result.

[`Result`]: std/result/index.html

> *Note:* A panicked task does not currently produce a useful error
> *Note:* A panicked thread does not currently produce a useful error
> value (`try` always returns `Err(())`). In the
> future, it may be possible for tasks to intercept the value passed to
> future, it may be possible for threads to intercept the value passed to
> `panic!()`.

But not all panics are created equal. In some cases you might need to abort
the entire program (perhaps you're writing an assert which, if it trips,
indicates an unrecoverable logic error); in other cases you might want to
contain the panic at a certain boundary (perhaps a small piece of input from
the outside world, which you happen to be processing in parallel, is malformed
such that the processing task cannot proceed).
such that the processing thread cannot proceed).
Loading