1 % The Rust Tasks and Communication Guide
5 Rust provides safe concurrency through a combination
6 of lightweight, memory-isolated tasks and message passing.
7 This guide will describe the concurrency model in Rust, how it
8 relates to the Rust type system, and introduce
9 the fundamental library abstractions for constructing concurrent programs.
11 Rust tasks are not the same as traditional threads: rather,
12 they are considered _green threads_, lightweight units of execution that the Rust
13 runtime schedules cooperatively onto a small number of operating system threads.
14 On a multi-core system Rust tasks will be scheduled in parallel by default.
15 Because tasks are significantly
16 cheaper to create than traditional threads, Rust can create hundreds of
17 thousands of concurrent tasks on a typical 32-bit system.
18 In general, all Rust code executes inside a task, including the `main` function.
20 In order to make efficient use of memory Rust tasks have dynamically sized stacks.
21 A task begins its life with a small
22 amount of stack space (currently in the low thousands of bytes, depending on
23 platform), and acquires more stack as needed.
24 Unlike in languages such as C, a Rust task cannot accidentally write to
25 memory beyond the end of the stack, causing crashes or worse.
27 Tasks provide failure isolation and recovery. When a fatal error occurs in Rust
28 code as a result of an explicit call to `fail!()`, an assertion failure, or
29 another invalid operation, the runtime system destroys the entire
30 task. Unlike in languages such as Java and C++, there is no way to `catch` an
31 exception. Instead, tasks may monitor each other for failure.
33 Tasks use Rust's type system to provide strong memory safety guarantees. In
34 particular, the type system guarantees that tasks cannot share mutable state
35 with each other. Tasks communicate with each other by transferring _owned_
36 data through the global _exchange heap_.
38 ## A note about the libraries
40 While Rust's type system provides the building blocks needed for safe
41 and efficient tasks, all of the task functionality itself is implemented
42 in the standard and sync libraries, which are still under development
43 and do not always present a consistent or complete interface.
45 For your reference, these are the standard modules involved in Rust
46 concurrency at this writing:
48 * [`std::task`] - All code relating to tasks and task scheduling,
49 * [`std::comm`] - The message passing interface,
50 * [`sync::DuplexStream`] - An extension of `pipes::stream` that allows both sending and receiving,
51 * [`sync::Arc`] - The Arc (atomically reference counted) type, for safely sharing immutable data,
52 * [`sync::Semaphore`] - A counting, blocking, bounded-waiting semaphore,
53 * [`sync::Mutex`] - A blocking, bounded-waiting, mutual exclusion lock with an associated
54 FIFO condition variable,
55 * [`sync::RWLock`] - A blocking, no-starvation, reader-writer lock with an associated condvar,
56 * [`sync::Barrier`] - A barrier enables multiple tasks to synchronize the beginning
58 * [`sync::TaskPool`] - A task pool abstraction,
59 * [`sync::Future`] - A type encapsulating the result of a computation which may not be complete,
60 * [`sync::one`] - A "once initialization" primitive
61 * [`sync::mutex`] - A proper mutex implementation regardless of the "flavor of task" which is
64 [`std::task`]: std/task/index.html
65 [`std::comm`]: std/comm/index.html
66 [`sync::DuplexStream`]: sync/struct.DuplexStream.html
67 [`sync::Arc`]: sync/struct.Arc.html
68 [`sync::Semaphore`]: sync/raw/struct.Semaphore.html
69 [`sync::Mutex`]: sync/struct.Mutex.html
70 [`sync::RWLock`]: sync/struct.RWLock.html
71 [`sync::Barrier`]: sync/struct.Barrier.html
72 [`sync::TaskPool`]: sync/struct.TaskPool.html
73 [`sync::Future`]: sync/struct.Future.html
74 [`sync::one`]: sync/one/index.html
75 [`sync::mutex`]: sync/mutex/index.html
79 The programming interface for creating and managing tasks lives
80 in the `task` module of the `std` library, and is thus available to all
81 Rust code by default. At its simplest, creating a task is a matter of
82 calling the `spawn` function with a closure argument. `spawn` executes the
83 closure in the new task.
86 # use std::task::spawn;
88 // Print something profound in a different task using a named function
89 fn print_message() { println!("I am running in a different task!"); }
92 // Alternatively, use a `proc` expression instead of a named function.
93 // The `proc` expression evaluates to an (unnamed) owned closure.
94 // That closure will call `println!(...)` when the spawned task runs.
95 spawn(proc() println!("I am also running in a different task!") );
98 In Rust, there is nothing special about creating tasks: a task is not a
99 concept that appears in the language semantics. Instead, Rust's type system
100 provides all the tools necessary to implement safe concurrency: particularly,
101 _owned types_. The language leaves the implementation details to the standard
104 The `spawn` function has a very simple type signature: `fn spawn(f:
105 proc())`. Because it accepts only owned closures, and owned closures
106 contain only owned data, `spawn` can safely move the entire closure
107 and all its associated state into an entirely different task for
108 execution. Like any closure, the function passed to `spawn` may capture
109 an environment that it carries across tasks.
112 # use std::task::spawn;
113 # fn generate_task_number() -> int { 0 }
114 // Generate some state locally
115 let child_task_number = generate_task_number();
118 // Capture it in the remote task
119 println!("I am child number {}", child_task_number);
125 Now that we have spawned a new task, it would be nice if we could
126 communicate with it. Recall that Rust does not have shared mutable
127 state, so one task may not manipulate variables owned by another task.
128 Instead we use *pipes*.
130 A pipe is simply a pair of endpoints: one for sending messages and another for
131 receiving messages. Pipes are low-level communication building-blocks and so
132 come in a variety of forms, each one appropriate for a different use case. In
133 what follows, we cover the most commonly used varieties.
135 The simplest way to create a pipe is to use the `channel`
136 function to create a `(Sender, Receiver)` pair. In Rust parlance, a *sender*
137 is a sending endpoint of a pipe, and a *receiver* is the receiving
138 endpoint. Consider the following example of calculating two results
142 # use std::task::spawn;
144 let (tx, rx): (Sender<int>, Receiver<int>) = channel();
147 let result = some_expensive_computation();
151 some_other_expensive_computation();
152 let result = rx.recv();
153 # fn some_expensive_computation() -> int { 42 }
154 # fn some_other_expensive_computation() {}
157 Let's examine this example in detail. First, the `let` statement creates a
158 stream for sending and receiving integers (the left-hand side of the `let`,
159 `(tx, rx)`, is an example of a *destructuring let*: the pattern separates
160 a tuple into its component parts).
163 let (tx, rx): (Sender<int>, Receiver<int>) = channel();
166 The child task will use the sender to send data to the parent task,
167 which will wait to receive the data on the receiver. The next statement
168 spawns the child task.
171 # use std::task::spawn;
172 # fn some_expensive_computation() -> int { 42 }
173 # let (tx, rx) = channel();
175 let result = some_expensive_computation();
180 Notice that the creation of the task closure transfers `tx` to the child
181 task implicitly: the closure captures `tx` in its environment. Both `Sender`
182 and `Receiver` are sendable types and may be captured into tasks or otherwise
183 transferred between them. In the example, the child task runs an expensive
184 computation, then sends the result over the captured channel.
186 Finally, the parent continues with some other expensive
187 computation, then waits for the child's result to arrive on the
191 # fn some_other_expensive_computation() {}
192 # let (tx, rx) = channel::<int>();
194 some_other_expensive_computation();
195 let result = rx.recv();
198 The `Sender` and `Receiver` pair created by `channel` enables efficient
199 communication between a single sender and a single receiver, but multiple
200 senders cannot use a single `Sender` value, and multiple receivers cannot use a
201 single `Receiver` value. What if our example needed to compute multiple
202 results across a number of tasks? The following program is ill-typed:
205 # fn some_expensive_computation() -> int { 42 }
206 let (tx, rx) = channel();
209 tx.send(some_expensive_computation());
212 // ERROR! The previous spawn statement already owns the sender,
213 // so the compiler will not allow it to be captured again
215 tx.send(some_expensive_computation());
219 Instead we can clone the `tx`, which allows for multiple senders.
222 let (tx, rx) = channel();
224 for init_val in range(0u, 3) {
225 // Create a new channel handle to distribute to the child task
226 let child_tx = tx.clone();
228 child_tx.send(some_expensive_computation(init_val));
232 let result = rx.recv() + rx.recv() + rx.recv();
233 # fn some_expensive_computation(_i: uint) -> int { 42 }
236 Cloning a `Sender` produces a new handle to the same channel, allowing multiple
237 tasks to send data to a single receiver. It upgrades the channel internally in
238 order to allow this functionality, which means that channels that are not
239 cloned can avoid the overhead required to handle multiple senders. But this
240 fact has no bearing on the channel's usage: the upgrade is transparent.
242 Note that the above cloning example is somewhat contrived since
243 you could also simply use three `Sender` pairs, but it serves to
244 illustrate the point. For reference, written with multiple streams, it
245 might look like the example below.
248 # use std::task::spawn;
250 // Create a vector of ports, one for each child task
251 let rxs = Vec::from_fn(3, |init_val| {
252 let (tx, rx) = channel();
254 tx.send(some_expensive_computation(init_val));
259 // Wait on each port, accumulating the results
260 let result = rxs.iter().fold(0, |accum, rx| accum + rx.recv() );
261 # fn some_expensive_computation(_i: uint) -> int { 42 }
264 ## Backgrounding computations: Futures
265 With `sync::Future`, rust has a mechanism for requesting a computation and getting the result
268 The basic example below illustrates this.
271 use std::sync::Future;
274 # fn make_a_sandwich() {};
275 fn fib(n: u64) -> u64 {
276 // lengthy computation returning an uint
280 let mut delayed_fib = Future::spawn(proc() fib(50));
282 println!("fib(50) = {}", delayed_fib.get())
286 The call to `future::spawn` returns immediately a `future` object regardless of how long it
287 takes to run `fib(50)`. You can then make yourself a sandwich while the computation of `fib` is
288 running. The result of the execution of the method is obtained by calling `get` on the future.
289 This call will block until the value is available (*i.e.* the computation is complete). Note that
290 the future needs to be mutable so that it can save the result for next time `get` is called.
292 Here is another example showing how futures allow you to background computations. The workload will
293 be distributed on the available cores.
296 # use std::sync::Future;
297 fn partial_sum(start: uint) -> f64 {
298 let mut local_sum = 0f64;
299 for num in range(start*100000, (start+1)*100000) {
300 local_sum += (num as f64 + 1.0).powf(-2.0);
306 let mut futures = Vec::from_fn(1000, |ind| Future::spawn( proc() { partial_sum(ind) }));
308 let mut final_res = 0f64;
309 for ft in futures.mut_iter() {
310 final_res += ft.get();
312 println!("π^2/6 is not far from : {}", final_res);
316 ## Sharing immutable data without copy: Arc
318 To share immutable data between tasks, a first approach would be to only use pipes as we have seen
319 previously. A copy of the data to share would then be made for each task. In some cases, this would
320 add up to a significant amount of wasted memory and would require copying the same data more than
323 To tackle this issue, one can use an Atomically Reference Counted wrapper (`Arc`) as implemented in
324 the `sync` library of Rust. With an Arc, the data will no longer be copied for each task. The Arc
325 acts as a reference to the shared data and only this reference is shared and cloned.
327 Here is a small example showing how to use Arcs. We wish to run concurrently several computations on
328 a single large vector of floats. Each task needs the full vector to perform its duty.
334 fn pnorm(nums: &[f64], p: uint) -> f64 {
335 nums.iter().fold(0.0, |a, b| a + b.powf(p as f64)).powf(1.0 / (p as f64))
339 let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
340 let numbers_arc = Arc::new(numbers);
342 for num in range(1u, 10) {
343 let task_numbers = numbers_arc.clone();
346 println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
352 The function `pnorm` performs a simple computation on the vector (it computes the sum of its items
353 at the power given as argument and takes the inverse power of this value). The Arc on the vector is
358 # use std::sync::Arc;
360 # let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
361 let numbers_arc = Arc::new(numbers);
365 and a unique clone is captured for each task via a procedure. This only copies the wrapper and not
366 it's contents. Within the task's procedure, the captured Arc reference can be used as an immutable
367 reference to the underlying vector as if it were local.
371 # use std::sync::Arc;
372 # fn pnorm(nums: &[f64], p: uint) -> f64 { 4.0 }
374 # let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
375 # let numbers_arc = Arc::new(numbers);
377 let task_numbers = numbers_arc.clone();
379 // Capture task_numbers and use it as if it was the underlying vector
380 println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
385 The `arc` module also implements Arcs around mutable data that are not covered here.
387 # Handling task failure
389 Rust has a built-in mechanism for raising exceptions. The `fail!()` macro
390 (which can also be written with an error string as an argument: `fail!(
391 ~reason)`) and the `assert!` construct (which effectively calls `fail!()`
392 if a boolean expression is false) are both ways to raise exceptions. When a
393 task raises an exception the task unwinds its stack---running destructors and
394 freeing memory along the way---and then exits. Unlike exceptions in C++,
395 exceptions in Rust are unrecoverable within a single task: once a task fails,
396 there is no way to "catch" the exception.
398 While it isn't possible for a task to recover from failure, tasks may notify
399 each other of failure. The simplest way of handling task failure is with the
400 `try` function, which is similar to `spawn`, but immediately blocks waiting
401 for the child task to finish. `try` returns a value of type `Result<T,
402 ()>`. `Result` is an `enum` type with two variants: `Ok` and `Err`. In this
403 case, because the type arguments to `Result` are `int` and `()`, callers can
404 pattern-match on a result to check whether it's an `Ok` result with an `int`
405 field (representing a successful result) or an `Err` result (representing
406 termination with an error).
408 ~~~{.ignore .linked-failure}
410 # fn some_condition() -> bool { false }
411 # fn calculate_result() -> int { 0 }
412 let result: Result<int, ()> = task::try(proc() {
413 if some_condition() {
419 assert!(result.is_err());
422 Unlike `spawn`, the function spawned using `try` may return a value,
423 which `try` will dutifully propagate back to the caller in a [`Result`]
424 enum. If the child task terminates successfully, `try` will
425 return an `Ok` result; if the child task fails, `try` will return
428 [`Result`]: std/result/index.html
430 > *Note:* A failed task does not currently produce a useful error
431 > value (`try` always returns `Err(())`). In the
432 > future, it may be possible for tasks to intercept the value passed to
435 TODO: Need discussion of `future_result` in order to make failure
438 But not all failures are created equal. In some cases you might need to
439 abort the entire program (perhaps you're writing an assert which, if
440 it trips, indicates an unrecoverable logic error); in other cases you
441 might want to contain the failure at a certain boundary (perhaps a
442 small piece of input from the outside world, which you happen to be
443 processing in parallel, is malformed and its processing task can't
446 ## Creating a task with a bi-directional communication path
448 A very common thing to do is to spawn a child task where the parent
449 and child both need to exchange messages with each other. The
450 function `sync::comm::duplex` supports this pattern. We'll
451 look briefly at how to use it.
453 To see how `duplex` works, we will create a child task
454 that repeatedly receives a `uint` message, converts it to a string, and sends
455 the string in response. The child terminates when it receives `0`.
456 Here is the function that implements the child task:
459 #![allow(deprecated)]
461 use std::comm::DuplexStream;
463 fn stringifier(channel: &DuplexStream<String, uint>) {
466 value = channel.recv();
467 channel.send(value.to_string());
468 if value == 0 { break; }
474 The implementation of `DuplexStream` supports both sending and
475 receiving. The `stringifier` function takes a `DuplexStream` that can
476 send strings (the first type parameter) and receive `uint` messages
477 (the second type parameter). The body itself simply loops, reading
478 from the channel and then sending its response back. The actual
479 response itself is simply the stringified version of the received value,
480 `uint::to_string(value)`.
482 Here is the code for the parent task:
485 #![allow(deprecated)]
487 use std::comm::duplex;
488 # use std::task::spawn;
489 # use std::comm::DuplexStream;
490 # fn stringifier(channel: &DuplexStream<String, uint>) {
491 # let mut value: uint;
493 # value = channel.recv();
494 # channel.send(value.to_string());
495 # if value == 0u { break; }
500 let (from_child, to_child) = duplex();
503 stringifier(&to_child);
507 assert!(from_child.recv().as_slice() == "22");
512 assert!(from_child.recv().as_slice() == "23");
513 assert!(from_child.recv().as_slice() == "0");
518 The parent task first calls `DuplexStream` to create a pair of bidirectional
519 endpoints. It then uses `task::spawn` to create the child task, which captures
520 one end of the communication channel. As a result, both parent and child can
521 send and receive data to and from the other.