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 use std::sync::Future;
212 # fn make_a_sandwich() {};
213 fn fib(n: u64) -> u64 {
214 // lengthy computation returning an uint
218 let mut delayed_fib = Future::spawn(move || fib(50));
220 println!("fib(50) = {}", delayed_fib.get())
224 The call to `future::spawn` immediately returns a `future` object regardless of
225 how long it takes to run `fib(50)`. You can then make yourself a sandwich while
226 the computation of `fib` is running. The result of the execution of the method
227 is obtained by calling `get` on the future. This call will block until the
228 value is available (*i.e.* the computation is complete). Note that the future
229 needs to be mutable so that it can save the result for next time `get` is
232 Here is another example showing how futures allow you to background
233 computations. The workload will be distributed on the available cores.
236 # use std::num::Float;
237 # use std::sync::Future;
238 fn partial_sum(start: uint) -> f64 {
239 let mut local_sum = 0f64;
240 for num in range(start*100000, (start+1)*100000) {
241 local_sum += (num as f64 + 1.0).powf(-2.0);
247 let mut futures = Vec::from_fn(200, |ind| Future::spawn(move || partial_sum(ind)));
249 let mut final_res = 0f64;
250 for ft in futures.iter_mut() {
251 final_res += ft.get();
253 println!("π^2/6 is not far from : {}", final_res);
257 ## Sharing without copying: Arc
259 To share data between threads, a first approach would be to only use channel as
260 we have seen previously. A copy of the data to share would then be made for
261 each thread. In some cases, this would add up to a significant amount of wasted
262 memory and would require copying the same data more than necessary.
264 To tackle this issue, one can use an Atomically Reference Counted wrapper
265 (`Arc`) as implemented in the `sync` library of Rust. With an Arc, the data
266 will no longer be copied for each thread. The Arc acts as a reference to the
267 shared data and only this reference is shared and cloned.
269 Here is a small example showing how to use Arcs. We wish to run concurrently
270 several computations on a single large vector of floats. Each thread needs the
271 full vector to perform its duty.
278 fn pnorm(nums: &[f64], p: uint) -> f64 {
279 nums.iter().fold(0.0, |a, b| a + b.powf(p as f64)).powf(1.0 / (p as f64))
283 let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
284 let numbers_arc = Arc::new(numbers);
286 for num in range(1u, 10) {
287 let thread_numbers = numbers_arc.clone();
290 println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
296 The function `pnorm` performs a simple computation on the vector (it computes
297 the sum of its items at the power given as argument and takes the inverse power
298 of this value). The Arc on the vector is created by the line:
302 # use std::sync::Arc;
304 # let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
305 let numbers_arc = Arc::new(numbers);
309 and a clone is captured for each thread via a procedure. This only copies
310 the wrapper and not its contents. Within the thread's procedure, the captured
311 Arc reference can be used as a shared reference to the underlying vector as
316 # use std::sync::Arc;
317 # fn pnorm(nums: &[f64], p: uint) -> f64 { 4.0 }
319 # let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
320 # let numbers_arc = Arc::new(numbers);
322 let thread_numbers = numbers_arc.clone();
324 // Capture thread_numbers and use it as if it was the underlying vector
325 println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
330 # Handling thread panics
332 Rust has a built-in mechanism for raising exceptions. The `panic!()` macro
333 (which can also be written with an error string as an argument: `panic!(
334 ~reason)`) and the `assert!` construct (which effectively calls `panic!()` if a
335 boolean expression is false) are both ways to raise exceptions. When a thread
336 raises an exception, the thread unwinds its stack—running destructors and
337 freeing memory along the way—and then exits. Unlike exceptions in C++,
338 exceptions in Rust are unrecoverable within a single thread: once a thread panics,
339 there is no way to "catch" the exception.
341 While it isn't possible for a thread to recover from panicking, threads may notify
342 each other if they panic. The simplest way of handling a panic is with the
343 `try` function, which is similar to `spawn`, but immediately blocks and waits
344 for the child thread to finish. `try` returns a value of type
345 `Result<T, Box<Any + Send>>`. `Result` is an `enum` type with two variants:
346 `Ok` and `Err`. In this case, because the type arguments to `Result` are `int`
347 and `()`, callers can pattern-match on a result to check whether it's an `Ok`
348 result with an `int` field (representing a successful result) or an `Err` result
349 (representing termination with an error).
352 # use std::thread::Thread;
353 # fn some_condition() -> bool { false }
354 # fn calculate_result() -> int { 0 }
355 let result: Result<int, Box<std::any::Any + Send>> = Thread::spawn(move || {
356 if some_condition() {
362 assert!(result.is_err());
365 Unlike `spawn`, the function spawned using `try` may return a value, which
366 `try` will dutifully propagate back to the caller in a [`Result`] enum. If the
367 child thread terminates successfully, `try` will return an `Ok` result; if the
368 child thread panics, `try` will return an `Error` result.
370 [`Result`]: std/result/index.html
372 > *Note:* A panicked thread does not currently produce a useful error
373 > value (`try` always returns `Err(())`). In the
374 > future, it may be possible for threads to intercept the value passed to
377 But not all panics are created equal. In some cases you might need to abort
378 the entire program (perhaps you're writing an assert which, if it trips,
379 indicates an unrecoverable logic error); in other cases you might want to
380 contain the panic at a certain boundary (perhaps a small piece of input from
381 the outside world, which you happen to be processing in parallel, is malformed
382 such that the processing thread cannot proceed).