]> git.lizzy.rs Git - rust.git/blob - src/doc/guide-tasks.md
doc: Remove all uses of `~str` from the documentation.
[rust.git] / src / doc / guide-tasks.md
1 % The Rust Tasks and Communication Guide
2
3 # Introduction
4
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.
10
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.
19
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.
26
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.
32
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_.
37
38 ## A note about the libraries
39
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.
44
45 For your reference, these are the standard modules involved in Rust
46 concurrency at this writing:
47
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
57     of some computation,
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
62     acquiring the lock.
63
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
76
77 # Basics
78
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.
84
85 ~~~~
86 # use std::task::spawn;
87
88 // Print something profound in a different task using a named function
89 fn print_message() { println!("I am running in a different task!"); }
90 spawn(print_message);
91
92 // Print something profound in a different task using a `proc` expression
93 // The `proc` expression evaluates to an (unnamed) owned closure.
94 // That closure will call `println!(...)` when the spawned task runs.
95
96 spawn(proc() println!("I am also running in a different task!") );
97 ~~~~
98
99 In Rust, there is nothing special about creating tasks: a task is not a
100 concept that appears in the language semantics. Instead, Rust's type system
101 provides all the tools necessary to implement safe concurrency: particularly,
102 _owned types_. The language leaves the implementation details to the standard
103 library.
104
105 The `spawn` function has a very simple type signature: `fn spawn(f:
106 proc())`. Because it accepts only owned closures, and owned closures
107 contain only owned data, `spawn` can safely move the entire closure
108 and all its associated state into an entirely different task for
109 execution. Like any closure, the function passed to `spawn` may capture
110 an environment that it carries across tasks.
111
112 ~~~
113 # use std::task::spawn;
114 # fn generate_task_number() -> int { 0 }
115 // Generate some state locally
116 let child_task_number = generate_task_number();
117
118 spawn(proc() {
119     // Capture it in the remote task
120     println!("I am child number {}", child_task_number);
121 });
122 ~~~
123
124 ## Communication
125
126 Now that we have spawned a new task, it would be nice if we could
127 communicate with it. Recall that Rust does not have shared mutable
128 state, so one task may not manipulate variables owned by another task.
129 Instead we use *pipes*.
130
131 A pipe is simply a pair of endpoints: one for sending messages and another for
132 receiving messages. Pipes are low-level communication building-blocks and so
133 come in a variety of forms, each one appropriate for a different use case. In
134 what follows, we cover the most commonly used varieties.
135
136 The simplest way to create a pipe is to use the `channel`
137 function to create a `(Sender, Receiver)` pair. In Rust parlance, a *sender*
138 is a sending endpoint of a pipe, and a *receiver* is the receiving
139 endpoint. Consider the following example of calculating two results
140 concurrently:
141
142 ~~~~
143 # use std::task::spawn;
144
145 let (tx, rx): (Sender<int>, Receiver<int>) = channel();
146
147 spawn(proc() {
148     let result = some_expensive_computation();
149     tx.send(result);
150 });
151
152 some_other_expensive_computation();
153 let result = rx.recv();
154 # fn some_expensive_computation() -> int { 42 }
155 # fn some_other_expensive_computation() {}
156 ~~~~
157
158 Let's examine this example in detail. First, the `let` statement creates a
159 stream for sending and receiving integers (the left-hand side of the `let`,
160 `(tx, rx)`, is an example of a *destructuring let*: the pattern separates
161 a tuple into its component parts).
162
163 ~~~~
164 let (tx, rx): (Sender<int>, Receiver<int>) = channel();
165 ~~~~
166
167 The child task will use the sender to send data to the parent task,
168 which will wait to receive the data on the receiver. The next statement
169 spawns the child task.
170
171 ~~~~
172 # use std::task::spawn;
173 # fn some_expensive_computation() -> int { 42 }
174 # let (tx, rx) = channel();
175 spawn(proc() {
176     let result = some_expensive_computation();
177     tx.send(result);
178 });
179 ~~~~
180
181 Notice that the creation of the task closure transfers `tx` to the child
182 task implicitly: the closure captures `tx` in its environment. Both `Sender`
183 and `Receiver` are sendable types and may be captured into tasks or otherwise
184 transferred between them. In the example, the child task runs an expensive
185 computation, then sends the result over the captured channel.
186
187 Finally, the parent continues with some other expensive
188 computation, then waits for the child's result to arrive on the
189 receiver:
190
191 ~~~~
192 # fn some_other_expensive_computation() {}
193 # let (tx, rx) = channel::<int>();
194 # tx.send(0);
195 some_other_expensive_computation();
196 let result = rx.recv();
197 ~~~~
198
199 The `Sender` and `Receiver` pair created by `channel` enables efficient
200 communication between a single sender and a single receiver, but multiple
201 senders cannot use a single `Sender` value, and multiple receivers cannot use a
202 single `Receiver` value.  What if our example needed to compute multiple
203 results across a number of tasks? The following program is ill-typed:
204
205 ~~~ {.ignore}
206 # fn some_expensive_computation() -> int { 42 }
207 let (tx, rx) = channel();
208
209 spawn(proc() {
210     tx.send(some_expensive_computation());
211 });
212
213 // ERROR! The previous spawn statement already owns the sender,
214 // so the compiler will not allow it to be captured again
215 spawn(proc() {
216     tx.send(some_expensive_computation());
217 });
218 ~~~
219
220 Instead we can clone the `tx`, which allows for multiple senders.
221
222 ~~~
223 let (tx, rx) = channel();
224
225 for init_val in range(0u, 3) {
226     // Create a new channel handle to distribute to the child task
227     let child_tx = tx.clone();
228     spawn(proc() {
229         child_tx.send(some_expensive_computation(init_val));
230     });
231 }
232
233 let result = rx.recv() + rx.recv() + rx.recv();
234 # fn some_expensive_computation(_i: uint) -> int { 42 }
235 ~~~
236
237 Cloning a `Sender` produces a new handle to the same channel, allowing multiple
238 tasks to send data to a single receiver. It upgrades the channel internally in
239 order to allow this functionality, which means that channels that are not
240 cloned can avoid the overhead required to handle multiple senders. But this
241 fact has no bearing on the channel's usage: the upgrade is transparent.
242
243 Note that the above cloning example is somewhat contrived since
244 you could also simply use three `Sender` pairs, but it serves to
245 illustrate the point. For reference, written with multiple streams, it
246 might look like the example below.
247
248 ~~~
249 # use std::task::spawn;
250
251 // Create a vector of ports, one for each child task
252 let rxs = Vec::from_fn(3, |init_val| {
253     let (tx, rx) = channel();
254     spawn(proc() {
255         tx.send(some_expensive_computation(init_val));
256     });
257     rx
258 });
259
260 // Wait on each port, accumulating the results
261 let result = rxs.iter().fold(0, |accum, rx| accum + rx.recv() );
262 # fn some_expensive_computation(_i: uint) -> int { 42 }
263 ~~~
264
265 ## Backgrounding computations: Futures
266 With `sync::Future`, rust has a mechanism for requesting a computation and getting the result
267 later.
268
269 The basic example below illustrates this.
270
271 ~~~
272 extern crate sync;
273
274 # fn main() {
275 # fn make_a_sandwich() {};
276 fn fib(n: u64) -> u64 {
277     // lengthy computation returning an uint
278     12586269025
279 }
280
281 let mut delayed_fib = sync::Future::spawn(proc() fib(50));
282 make_a_sandwich();
283 println!("fib(50) = {:?}", delayed_fib.get())
284 # }
285 ~~~
286
287 The call to `future::spawn` returns immediately a `future` object regardless of how long it
288 takes to run `fib(50)`. You can then make yourself a sandwich while the computation of `fib` is
289 running. The result of the execution of the method is obtained by calling `get` on the future.
290 This call will block until the value is available (*i.e.* the computation is complete). Note that
291 the future needs to be mutable so that it can save the result for next time `get` is called.
292
293 Here is another example showing how futures allow you to background computations. The workload will
294 be distributed on the available cores.
295
296 ~~~
297 # extern crate sync;
298 fn partial_sum(start: uint) -> f64 {
299     let mut local_sum = 0f64;
300     for num in range(start*100000, (start+1)*100000) {
301         local_sum += (num as f64 + 1.0).powf(-2.0);
302     }
303     local_sum
304 }
305
306 fn main() {
307     let mut futures = Vec::from_fn(1000, |ind| sync::Future::spawn( proc() { partial_sum(ind) }));
308
309     let mut final_res = 0f64;
310     for ft in futures.mut_iter()  {
311         final_res += ft.get();
312     }
313     println!("π^2/6 is not far from : {}", final_res);
314 }
315 ~~~
316
317 ## Sharing immutable data without copy: Arc
318
319 To share immutable data between tasks, a first approach would be to only use pipes as we have seen
320 previously. A copy of the data to share would then be made for each task. In some cases, this would
321 add up to a significant amount of wasted memory and would require copying the same data more than
322 necessary.
323
324 To tackle this issue, one can use an Atomically Reference Counted wrapper (`Arc`) as implemented in
325 the `sync` library of Rust. With an Arc, the data will no longer be copied for each task. The Arc
326 acts as a reference to the shared data and only this reference is shared and cloned.
327
328 Here is a small example showing how to use Arcs. We wish to run concurrently several computations on
329 a single large vector of floats. Each task needs the full vector to perform its duty.
330
331 ~~~
332 extern crate rand;
333 extern crate sync;
334
335 use sync::Arc;
336
337 fn pnorm(nums: &[f64], p: uint) -> f64 {
338     nums.iter().fold(0.0, |a, b| a + b.powf(p as f64)).powf(1.0 / (p as f64))
339 }
340
341 fn main() {
342     let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
343     let numbers_arc = Arc::new(numbers);
344
345     for num in range(1u, 10) {
346         let task_numbers = numbers_arc.clone();
347
348         spawn(proc() {
349             println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
350         });
351     }
352 }
353 ~~~
354
355 The function `pnorm` performs a simple computation on the vector (it computes the sum of its items
356 at the power given as argument and takes the inverse power of this value). The Arc on the vector is
357 created by the line
358
359 ~~~
360 # extern crate sync;
361 # extern crate rand;
362 # use sync::Arc;
363 # fn main() {
364 # let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
365 let numbers_arc=Arc::new(numbers);
366 # }
367 ~~~
368
369 and a unique clone is captured for each task via a procedure. This only copies the wrapper and not
370 it's contents. Within the task's procedure, the captured Arc reference can be used as an immutable
371 reference to the underlying vector as if it were local.
372
373 ~~~
374 # extern crate sync;
375 # extern crate rand;
376 # use sync::Arc;
377 # fn pnorm(nums: &[f64], p: uint) -> f64 { 4.0 }
378 # fn main() {
379 # let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
380 # let numbers_arc = Arc::new(numbers);
381 # let num = 4;
382 let task_numbers = numbers_arc.clone();
383 spawn(proc() {
384     // Capture task_numbers and use it as if it was the underlying vector
385     println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
386 });
387 # }
388 ~~~
389
390 The `arc` module also implements Arcs around mutable data that are not covered here.
391
392 # Handling task failure
393
394 Rust has a built-in mechanism for raising exceptions. The `fail!()` macro
395 (which can also be written with an error string as an argument: `fail!(
396 ~reason)`) and the `assert!` construct (which effectively calls `fail!()`
397 if a boolean expression is false) are both ways to raise exceptions. When a
398 task raises an exception the task unwinds its stack---running destructors and
399 freeing memory along the way---and then exits. Unlike exceptions in C++,
400 exceptions in Rust are unrecoverable within a single task: once a task fails,
401 there is no way to "catch" the exception.
402
403 While it isn't possible for a task to recover from failure, tasks may notify
404 each other of failure. The simplest way of handling task failure is with the
405 `try` function, which is similar to `spawn`, but immediately blocks waiting
406 for the child task to finish. `try` returns a value of type `Result<T,
407 ()>`. `Result` is an `enum` type with two variants: `Ok` and `Err`. In this
408 case, because the type arguments to `Result` are `int` and `()`, callers can
409 pattern-match on a result to check whether it's an `Ok` result with an `int`
410 field (representing a successful result) or an `Err` result (representing
411 termination with an error).
412
413 ~~~{.ignore .linked-failure}
414 # use std::task;
415 # fn some_condition() -> bool { false }
416 # fn calculate_result() -> int { 0 }
417 let result: Result<int, ()> = task::try(proc() {
418     if some_condition() {
419         calculate_result()
420     } else {
421         fail!("oops!");
422     }
423 });
424 assert!(result.is_err());
425 ~~~
426
427 Unlike `spawn`, the function spawned using `try` may return a value,
428 which `try` will dutifully propagate back to the caller in a [`Result`]
429 enum. If the child task terminates successfully, `try` will
430 return an `Ok` result; if the child task fails, `try` will return
431 an `Error` result.
432
433 [`Result`]: std/result/index.html
434
435 > *Note:* A failed task does not currently produce a useful error
436 > value (`try` always returns `Err(())`). In the
437 > future, it may be possible for tasks to intercept the value passed to
438 > `fail!()`.
439
440 TODO: Need discussion of `future_result` in order to make failure
441 modes useful.
442
443 But not all failures are created equal. In some cases you might need to
444 abort the entire program (perhaps you're writing an assert which, if
445 it trips, indicates an unrecoverable logic error); in other cases you
446 might want to contain the failure at a certain boundary (perhaps a
447 small piece of input from the outside world, which you happen to be
448 processing in parallel, is malformed and its processing task can't
449 proceed).
450
451 ## Creating a task with a bi-directional communication path
452
453 A very common thing to do is to spawn a child task where the parent
454 and child both need to exchange messages with each other. The
455 function `sync::comm::duplex` supports this pattern.  We'll
456 look briefly at how to use it.
457
458 To see how `duplex` works, we will create a child task
459 that repeatedly receives a `uint` message, converts it to a string, and sends
460 the string in response.  The child terminates when it receives `0`.
461 Here is the function that implements the child task:
462
463 ~~~
464 extern crate sync;
465 # fn main() {
466 fn stringifier(channel: &sync::DuplexStream<StrBuf, uint>) {
467     let mut value: uint;
468     loop {
469         value = channel.recv();
470         channel.send(value.to_str().to_strbuf());
471         if value == 0 { break; }
472     }
473 }
474 # }
475 ~~~
476
477 The implementation of `DuplexStream` supports both sending and
478 receiving. The `stringifier` function takes a `DuplexStream` that can
479 send strings (the first type parameter) and receive `uint` messages
480 (the second type parameter). The body itself simply loops, reading
481 from the channel and then sending its response back.  The actual
482 response itself is simply the stringified version of the received value,
483 `uint::to_str(value)`.
484
485 Here is the code for the parent task:
486
487 ~~~
488 extern crate sync;
489 # use std::task::spawn;
490 # use sync::DuplexStream;
491 # fn stringifier(channel: &sync::DuplexStream<StrBuf, uint>) {
492 #     let mut value: uint;
493 #     loop {
494 #         value = channel.recv();
495 #         channel.send(value.to_str().to_strbuf());
496 #         if value == 0u { break; }
497 #     }
498 # }
499 # fn main() {
500
501 let (from_child, to_child) = sync::duplex();
502
503 spawn(proc() {
504     stringifier(&to_child);
505 });
506
507 from_child.send(22);
508 assert!(from_child.recv().as_slice() == "22");
509
510 from_child.send(23);
511 from_child.send(0);
512
513 assert!(from_child.recv().as_slice() == "23");
514 assert!(from_child.recv().as_slice() == "0");
515
516 # }
517 ~~~
518
519 The parent task first calls `DuplexStream` to create a pair of bidirectional
520 endpoints. It then uses `task::spawn` to create the child task, which captures
521 one end of the communication channel.  As a result, both parent and child can
522 send and receive data to and from the other.