1 % The Rust Threads and Communication Guide
3 **NOTE** This guide is badly out of date and needs to be rewritten.
7 Rust provides safe concurrent abstractions through a number of core library
8 primitives. This guide will describe the concurrency model in Rust, how it
9 relates to the Rust type system, and introduce the fundamental library
10 abstractions for constructing concurrent programs.
12 Threads provide failure isolation and recovery. When a fatal error occurs in Rust
13 code as a result of an explicit call to `panic!()`, an assertion failure, or
14 another invalid operation, the runtime system destroys the entire thread. Unlike
15 in languages such as Java and C++, there is no way to `catch` an exception.
16 Instead, threads may monitor each other to see if they panic.
18 Threads use Rust's type system to provide strong memory safety guarantees. In
19 particular, the type system guarantees that threads cannot induce a data race
20 from shared mutable state.
24 At its simplest, creating a thread is a matter of calling the `spawn` function
25 with a closure argument. `spawn` executes the closure in the new thread.
28 # use std::thread::spawn;
30 // Print something profound in a different thread using a named function
31 fn print_message() { println!("I am running in a different thread!"); }
34 // Alternatively, use a `move ||` expression instead of a named function.
35 // `||` expressions evaluate to an unnamed closure. The `move` keyword
36 // indicates that the closure should take ownership of any variables it
38 spawn(move || println!("I am also running in a different thread!"));
41 In Rust, a thread is not a concept that appears in the language semantics.
42 Instead, Rust's type system provides all the tools necessary to implement safe
43 concurrency: particularly, ownership. The language leaves the implementation
44 details to the standard library.
46 The `spawn` function has the type signature: `fn
47 spawn<F:FnOnce()+Send>(f: F)`. This indicates that it takes as
48 argument a closure (of type `F`) that it will run exactly once. This
49 closure is limited to capturing `Send`-able data from its environment
50 (that is, data which is deeply owned). Limiting the closure to `Send`
51 ensures that `spawn` can safely move the entire closure and all its
52 associated state into an entirely different thread for execution.
55 # use std::thread::spawn;
56 # fn generate_thread_number() -> int { 0 }
57 // Generate some state locally
58 let child_thread_number = generate_thread_number();
61 // Capture it in the remote thread. The `move` keyword indicates
62 // that this closure should move `child_thread_number` into its
63 // environment, rather than capturing a reference into the
64 // enclosing stack frame.
65 println!("I am child number {}", child_thread_number);
71 Now that we have spawned a new thread, it would be nice if we could communicate
72 with it. For this, we use *channels*. A channel is simply a pair of endpoints:
73 one for sending messages and another for receiving messages.
75 The simplest way to create a channel is to use the `channel` function to create a
76 `(Sender, Receiver)` pair. In Rust parlance, a **sender** is a sending endpoint
77 of a channel, and a **receiver** is the receiving endpoint. Consider the following
78 example of calculating two results concurrently:
81 # use std::thread::spawn;
83 let (tx, rx): (Sender<int>, Receiver<int>) = channel();
86 let result = some_expensive_computation();
90 some_other_expensive_computation();
91 let result = rx.recv();
92 # fn some_expensive_computation() -> int { 42 }
93 # fn some_other_expensive_computation() {}
96 Let's examine this example in detail. First, the `let` statement creates a
97 stream for sending and receiving integers (the left-hand side of the `let`,
98 `(tx, rx)`, is an example of a destructuring let: the pattern separates a tuple
99 into its component parts).
102 let (tx, rx): (Sender<int>, Receiver<int>) = channel();
105 The child thread will use the sender to send data to the parent thread, which will
106 wait to receive the data on the receiver. The next statement spawns the child
110 # use std::thread::spawn;
111 # fn some_expensive_computation() -> int { 42 }
112 # let (tx, rx) = channel();
114 let result = some_expensive_computation();
119 Notice that the creation of the thread closure transfers `tx` to the child thread
120 implicitly: the closure captures `tx` in its environment. Both `Sender` and
121 `Receiver` are sendable types and may be captured into threads or otherwise
122 transferred between them. In the example, the child thread runs an expensive
123 computation, then sends the result over the captured channel.
125 Finally, the parent continues with some other expensive computation, then waits
126 for the child's result to arrive on the receiver:
129 # fn some_other_expensive_computation() {}
130 # let (tx, rx) = channel::<int>();
132 some_other_expensive_computation();
133 let result = rx.recv();
136 The `Sender` and `Receiver` pair created by `channel` enables efficient
137 communication between a single sender and a single receiver, but multiple
138 senders cannot use a single `Sender` value, and multiple receivers cannot use a
139 single `Receiver` value. What if our example needed to compute multiple
140 results across a number of threads? The following program is ill-typed:
143 # fn some_expensive_computation() -> int { 42 }
144 let (tx, rx) = channel();
147 tx.send(some_expensive_computation());
150 // ERROR! The previous spawn statement already owns the sender,
151 // so the compiler will not allow it to be captured again
153 tx.send(some_expensive_computation());
157 Instead we can clone the `tx`, which allows for multiple senders.
160 let (tx, rx) = channel();
162 for init_val in range(0u, 3) {
163 // Create a new channel handle to distribute to the child thread
164 let child_tx = tx.clone();
166 child_tx.send(some_expensive_computation(init_val));
170 let result = rx.recv() + rx.recv() + rx.recv();
171 # fn some_expensive_computation(_i: uint) -> int { 42 }
174 Cloning a `Sender` produces a new handle to the same channel, allowing multiple
175 threads to send data to a single receiver. It upgrades the channel internally in
176 order to allow this functionality, which means that channels that are not
177 cloned can avoid the overhead required to handle multiple senders. But this
178 fact has no bearing on the channel's usage: the upgrade is transparent.
180 Note that the above cloning example is somewhat contrived since you could also
181 simply use three `Sender` pairs, but it serves to illustrate the point. For
182 reference, written with multiple streams, it might look like the example below.
185 # use std::thread::spawn;
187 // Create a vector of ports, one for each child thread
188 let rxs = Vec::from_fn(3, |init_val| {
189 let (tx, rx) = channel();
191 tx.send(some_expensive_computation(init_val));
196 // Wait on each port, accumulating the results
197 let result = rxs.iter().fold(0, |accum, rx| accum + rx.recv() );
198 # fn some_expensive_computation(_i: uint) -> int { 42 }
201 ## Backgrounding computations: Futures
203 With `sync::Future`, rust has a mechanism for requesting a computation and
204 getting the result later.
206 The basic example below illustrates this.
209 # #![allow(deprecated)]
210 use std::sync::Future;
213 # fn make_a_sandwich() {};
214 fn fib(n: u64) -> u64 {
215 // lengthy computation returning an uint
219 let mut delayed_fib = Future::spawn(move || fib(50));
221 println!("fib(50) = {}", delayed_fib.get())
225 The call to `future::spawn` immediately returns a `future` object regardless of
226 how long it takes to run `fib(50)`. You can then make yourself a sandwich while
227 the computation of `fib` is running. The result of the execution of the method
228 is obtained by calling `get` on the future. This call will block until the
229 value is available (*i.e.* the computation is complete). Note that the future
230 needs to be mutable so that it can save the result for next time `get` is
233 Here is another example showing how futures allow you to background
234 computations. The workload will be distributed on the available cores.
237 # #![allow(deprecated)]
238 # use std::num::Float;
239 # use std::sync::Future;
240 fn partial_sum(start: uint) -> f64 {
241 let mut local_sum = 0f64;
242 for num in range(start*100000, (start+1)*100000) {
243 local_sum += (num as f64 + 1.0).powf(-2.0);
249 let mut futures = Vec::from_fn(200, |ind| Future::spawn(move || partial_sum(ind)));
251 let mut final_res = 0f64;
252 for ft in futures.iter_mut() {
253 final_res += ft.get();
255 println!("π^2/6 is not far from : {}", final_res);
259 ## Sharing without copying: Arc
261 To share data between threads, a first approach would be to only use channel as
262 we have seen previously. A copy of the data to share would then be made for
263 each thread. In some cases, this would add up to a significant amount of wasted
264 memory and would require copying the same data more than necessary.
266 To tackle this issue, one can use an Atomically Reference Counted wrapper
267 (`Arc`) as implemented in the `sync` library of Rust. With an Arc, the data
268 will no longer be copied for each thread. The Arc acts as a reference to the
269 shared data and only this reference is shared and cloned.
271 Here is a small example showing how to use Arcs. We wish to run concurrently
272 several computations on a single large vector of floats. Each thread needs the
273 full vector to perform its duty.
280 fn pnorm(nums: &[f64], p: uint) -> f64 {
281 nums.iter().fold(0.0, |a, b| a + b.powf(p as f64)).powf(1.0 / (p as f64))
285 let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
286 let numbers_arc = Arc::new(numbers);
288 for num in range(1u, 10) {
289 let thread_numbers = numbers_arc.clone();
292 println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
298 The function `pnorm` performs a simple computation on the vector (it computes
299 the sum of its items at the power given as argument and takes the inverse power
300 of this value). The Arc on the vector is created by the line:
304 # use std::sync::Arc;
306 # let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
307 let numbers_arc = Arc::new(numbers);
311 and a clone is captured for each thread via a procedure. This only copies
312 the wrapper and not its contents. Within the thread's procedure, the captured
313 Arc reference can be used as a shared reference to the underlying vector as
318 # use std::sync::Arc;
319 # fn pnorm(nums: &[f64], p: uint) -> f64 { 4.0 }
321 # let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
322 # let numbers_arc = Arc::new(numbers);
324 let thread_numbers = numbers_arc.clone();
326 // Capture thread_numbers and use it as if it was the underlying vector
327 println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
332 # Handling thread panics
334 Rust has a built-in mechanism for raising exceptions. The `panic!()` macro
335 (which can also be written with an error string as an argument: `panic!(
336 ~reason)`) and the `assert!` construct (which effectively calls `panic!()` if a
337 boolean expression is false) are both ways to raise exceptions. When a thread
338 raises an exception, the thread unwinds its stack—running destructors and
339 freeing memory along the way—and then exits. Unlike exceptions in C++,
340 exceptions in Rust are unrecoverable within a single thread: once a thread panics,
341 there is no way to "catch" the exception.
343 While it isn't possible for a thread to recover from panicking, threads may notify
344 each other if they panic. The simplest way of handling a panic is with the
345 `try` function, which is similar to `spawn`, but immediately blocks and waits
346 for the child thread to finish. `try` returns a value of type
347 `Result<T, Box<Any + Send>>`. `Result` is an `enum` type with two variants:
348 `Ok` and `Err`. In this case, because the type arguments to `Result` are `int`
349 and `()`, callers can pattern-match on a result to check whether it's an `Ok`
350 result with an `int` field (representing a successful result) or an `Err` result
351 (representing termination with an error).
354 # use std::thread::Thread;
355 # fn some_condition() -> bool { false }
356 # fn calculate_result() -> int { 0 }
357 let result: Result<int, Box<std::any::Any + Send>> = Thread::spawn(move || {
358 if some_condition() {
364 assert!(result.is_err());
367 Unlike `spawn`, the function spawned using `try` may return a value, which
368 `try` will dutifully propagate back to the caller in a [`Result`] enum. If the
369 child thread terminates successfully, `try` will return an `Ok` result; if the
370 child thread panics, `try` will return an `Error` result.
372 [`Result`]: std/result/index.html
374 > *Note:* A panicked thread does not currently produce a useful error
375 > value (`try` always returns `Err(())`). In the
376 > future, it may be possible for threads to intercept the value passed to
379 But not all panics are created equal. In some cases you might need to abort
380 the entire program (perhaps you're writing an assert which, if it trips,
381 indicates an unrecoverable logic error); in other cases you might want to
382 contain the panic at a certain boundary (perhaps a small piece of input from
383 the outside world, which you happen to be processing in parallel, is malformed
384 such that the processing thread cannot proceed).