2014-12-26 15:04:27 -06:00
|
|
|
% The Rust Threads and Communication Guide
|
2012-09-26 21:00:13 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
**NOTE** This guide is badly out of date and needs to be rewritten.
|
2014-12-14 02:05:32 -06:00
|
|
|
|
2012-09-26 21:00:13 -05:00
|
|
|
# Introduction
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
Rust provides safe concurrent abstractions through a number of core library
|
|
|
|
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.
|
2012-10-09 18:14:55 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
Threads provide failure isolation and recovery. When a fatal error occurs in Rust
|
2014-10-09 14:17:22 -05:00
|
|
|
code as a result of an explicit call to `panic!()`, an assertion failure, or
|
2014-12-26 15:04:27 -06:00
|
|
|
another invalid operation, the runtime system destroys the entire thread. Unlike
|
2014-08-25 20:15:20 -05:00
|
|
|
in languages such as Java and C++, there is no way to `catch` an exception.
|
2014-12-26 15:04:27 -06:00
|
|
|
Instead, threads may monitor each other to see if they panic.
|
2014-08-25 20:15:20 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
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
|
2014-08-25 20:15:20 -05:00
|
|
|
from shared mutable state.
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2012-10-01 17:41:21 -05:00
|
|
|
# Basics
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
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.
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-12-26 15:04:27 -06:00
|
|
|
# use std::thread::spawn;
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
// Print something profound in a different thread using a named function
|
|
|
|
fn print_message() { println!("I am running in a different thread!"); }
|
2012-10-01 17:41:21 -05:00
|
|
|
spawn(print_message);
|
|
|
|
|
2014-11-26 07:12:18 -06:00
|
|
|
// Alternatively, use a `move ||` expression instead of a named function.
|
2014-11-26 09:02:46 -06:00
|
|
|
// `||` expressions evaluate to an unnamed closure. The `move` keyword
|
2014-11-26 07:12:18 -06:00
|
|
|
// indicates that the closure should take ownership of any variables it
|
|
|
|
// touches.
|
2014-12-26 15:04:27 -06:00
|
|
|
spawn(move || println!("I am also running in a different thread!"));
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
In Rust, a thread is not a concept that appears in the language semantics.
|
2014-08-25 20:15:20 -05:00
|
|
|
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.
|
|
|
|
|
2014-11-26 07:12:18 -06:00
|
|
|
The `spawn` function has the type signature: `fn
|
|
|
|
spawn<F:FnOnce()+Send>(f: F)`. This indicates that it takes as
|
|
|
|
argument a closure (of type `F`) that it will run exactly once. This
|
2014-11-26 09:02:46 -06:00
|
|
|
closure is limited to capturing `Send`-able data from its environment
|
2014-11-26 07:12:18 -06:00
|
|
|
(that is, data which is deeply owned). Limiting the closure to `Send`
|
|
|
|
ensures that `spawn` can safely move the entire closure and all its
|
2014-12-26 15:04:27 -06:00
|
|
|
associated state into an entirely different thread for execution.
|
2014-08-25 20:15:20 -05:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-12-26 15:04:27 -06:00
|
|
|
# use std::thread::spawn;
|
|
|
|
# fn generate_thread_number() -> int { 0 }
|
2012-10-01 17:41:21 -05:00
|
|
|
// Generate some state locally
|
2014-12-26 15:04:27 -06:00
|
|
|
let child_thread_number = generate_thread_number();
|
2012-10-01 17:41:21 -05:00
|
|
|
|
2014-11-26 07:12:18 -06:00
|
|
|
spawn(move || {
|
2014-12-26 15:04:27 -06:00
|
|
|
// Capture it in the remote thread. The `move` keyword indicates
|
|
|
|
// that this closure should move `child_thread_number` into its
|
2014-11-26 07:12:18 -06:00
|
|
|
// environment, rather than capturing a reference into the
|
|
|
|
// enclosing stack frame.
|
2014-12-26 15:04:27 -06:00
|
|
|
println!("I am child number {}", child_thread_number);
|
2014-01-27 23:53:01 -06:00
|
|
|
});
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2012-10-01 17:41:21 -05:00
|
|
|
|
|
|
|
## Communication
|
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
Now that we have spawned a new thread, it would be nice if we could communicate
|
2014-08-25 20:15:20 -05:00
|
|
|
with it. For this, we use *channels*. A channel is simply a pair of endpoints:
|
|
|
|
one for sending messages and another for receiving messages.
|
2012-10-01 17:41:21 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
The simplest way to create a channel is to use the `channel` function to create a
|
|
|
|
`(Sender, Receiver)` pair. In Rust parlance, a **sender** is a sending endpoint
|
|
|
|
of a channel, and a **receiver** is the receiving endpoint. Consider the following
|
|
|
|
example of calculating two results concurrently:
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-12-26 15:04:27 -06:00
|
|
|
# use std::thread::spawn;
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-03-09 16:58:32 -05:00
|
|
|
let (tx, rx): (Sender<int>, Receiver<int>) = channel();
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-11-26 07:12:18 -06:00
|
|
|
spawn(move || {
|
2012-09-22 17:33:50 -05:00
|
|
|
let result = some_expensive_computation();
|
2014-03-09 16:58:32 -05:00
|
|
|
tx.send(result);
|
2014-01-27 23:53:01 -06:00
|
|
|
});
|
2012-09-22 17:33:50 -05:00
|
|
|
|
|
|
|
some_other_expensive_computation();
|
2014-03-09 16:58:32 -05:00
|
|
|
let result = rx.recv();
|
2012-09-22 17:33:50 -05:00
|
|
|
# fn some_expensive_computation() -> int { 42 }
|
|
|
|
# fn some_other_expensive_computation() {}
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2012-10-09 18:14:55 -05:00
|
|
|
Let's examine this example in detail. First, the `let` statement creates a
|
|
|
|
stream for sending and receiving integers (the left-hand side of the `let`,
|
2014-08-25 20:15:20 -05:00
|
|
|
`(tx, rx)`, is an example of a destructuring let: the pattern separates a tuple
|
|
|
|
into its component parts).
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-03-09 16:58:32 -05:00
|
|
|
let (tx, rx): (Sender<int>, Receiver<int>) = channel();
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
The child thread will use the sender to send data to the parent thread, which will
|
2014-08-25 20:15:20 -05:00
|
|
|
wait to receive the data on the receiver. The next statement spawns the child
|
2014-12-26 15:04:27 -06:00
|
|
|
thread.
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-12-26 15:04:27 -06:00
|
|
|
# use std::thread::spawn;
|
2012-09-22 17:33:50 -05:00
|
|
|
# fn some_expensive_computation() -> int { 42 }
|
2014-03-09 16:58:32 -05:00
|
|
|
# let (tx, rx) = channel();
|
2014-11-26 07:12:18 -06:00
|
|
|
spawn(move || {
|
2012-09-22 17:33:50 -05:00
|
|
|
let result = some_expensive_computation();
|
2014-03-09 16:58:32 -05:00
|
|
|
tx.send(result);
|
2014-01-27 23:53:01 -06:00
|
|
|
});
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
Notice that the creation of the thread closure transfers `tx` to the child thread
|
2014-08-25 20:15:20 -05:00
|
|
|
implicitly: the closure captures `tx` in its environment. Both `Sender` and
|
2014-12-26 15:04:27 -06:00
|
|
|
`Receiver` are sendable types and may be captured into threads or otherwise
|
|
|
|
transferred between them. In the example, the child thread runs an expensive
|
2012-10-09 18:14:55 -05:00
|
|
|
computation, then sends the result over the captured channel.
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
Finally, the parent continues with some other expensive computation, then waits
|
|
|
|
for the child's result to arrive on the receiver:
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2012-09-22 17:33:50 -05:00
|
|
|
# fn some_other_expensive_computation() {}
|
2014-03-09 16:58:32 -05:00
|
|
|
# let (tx, rx) = channel::<int>();
|
|
|
|
# tx.send(0);
|
2012-09-22 17:33:50 -05:00
|
|
|
some_other_expensive_computation();
|
2014-03-09 16:58:32 -05:00
|
|
|
let result = rx.recv();
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2012-09-22 17:33:50 -05:00
|
|
|
|
2014-03-09 16:58:32 -05:00
|
|
|
The `Sender` and `Receiver` pair created by `channel` enables efficient
|
2013-12-15 20:17:43 -06:00
|
|
|
communication between a single sender and a single receiver, but multiple
|
2014-03-09 16:58:32 -05:00
|
|
|
senders cannot use a single `Sender` value, and multiple receivers cannot use a
|
|
|
|
single `Receiver` value. What if our example needed to compute multiple
|
2014-12-26 15:04:27 -06:00
|
|
|
results across a number of threads? The following program is ill-typed:
|
2012-10-01 20:03:09 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
```{rust,ignore}
|
2012-10-01 20:03:09 -05:00
|
|
|
# fn some_expensive_computation() -> int { 42 }
|
2014-03-09 16:58:32 -05:00
|
|
|
let (tx, rx) = channel();
|
2012-10-01 20:03:09 -05:00
|
|
|
|
2014-11-26 07:12:18 -06:00
|
|
|
spawn(move || {
|
2014-03-09 16:58:32 -05:00
|
|
|
tx.send(some_expensive_computation());
|
2014-01-27 23:53:01 -06:00
|
|
|
});
|
2012-10-01 20:03:09 -05:00
|
|
|
|
2014-03-09 16:58:32 -05:00
|
|
|
// ERROR! The previous spawn statement already owns the sender,
|
2012-10-01 20:03:09 -05:00
|
|
|
// so the compiler will not allow it to be captured again
|
2014-11-26 07:12:18 -06:00
|
|
|
spawn(move || {
|
2014-03-09 16:58:32 -05:00
|
|
|
tx.send(some_expensive_computation());
|
2014-01-27 23:53:01 -06:00
|
|
|
});
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2012-10-01 20:03:09 -05:00
|
|
|
|
2014-03-09 16:58:32 -05:00
|
|
|
Instead we can clone the `tx`, which allows for multiple senders.
|
2012-10-01 17:41:21 -05:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-03-09 16:58:32 -05:00
|
|
|
let (tx, rx) = channel();
|
2012-10-01 17:41:21 -05:00
|
|
|
|
2013-08-03 11:45:23 -05:00
|
|
|
for init_val in range(0u, 3) {
|
2014-12-26 15:04:27 -06:00
|
|
|
// Create a new channel handle to distribute to the child thread
|
2014-03-09 16:58:32 -05:00
|
|
|
let child_tx = tx.clone();
|
2014-11-26 07:12:18 -06:00
|
|
|
spawn(move || {
|
2014-03-09 16:58:32 -05:00
|
|
|
child_tx.send(some_expensive_computation(init_val));
|
2014-01-27 23:53:01 -06:00
|
|
|
});
|
2012-10-01 17:41:21 -05:00
|
|
|
}
|
|
|
|
|
2014-03-09 16:58:32 -05:00
|
|
|
let result = rx.recv() + rx.recv() + rx.recv();
|
2012-10-01 17:41:21 -05:00
|
|
|
# fn some_expensive_computation(_i: uint) -> int { 42 }
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2012-10-01 17:41:21 -05:00
|
|
|
|
2014-03-09 16:58:32 -05:00
|
|
|
Cloning a `Sender` produces a new handle to the same channel, allowing multiple
|
2014-12-26 15:04:27 -06:00
|
|
|
threads to send data to a single receiver. It upgrades the channel internally in
|
2014-02-17 04:32:30 -06:00
|
|
|
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.
|
2012-10-01 17:41:21 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
Note that the above cloning example is somewhat contrived since you could also
|
|
|
|
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.
|
2012-10-01 17:41:21 -05:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-12-26 15:04:27 -06:00
|
|
|
# use std::thread::spawn;
|
2012-10-01 17:41:21 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
// Create a vector of ports, one for each child thread
|
2014-04-17 17:59:07 -05:00
|
|
|
let rxs = Vec::from_fn(3, |init_val| {
|
2014-03-09 16:58:32 -05:00
|
|
|
let (tx, rx) = channel();
|
2014-11-26 07:12:18 -06:00
|
|
|
spawn(move || {
|
2014-03-09 16:58:32 -05:00
|
|
|
tx.send(some_expensive_computation(init_val));
|
2014-01-27 23:53:01 -06:00
|
|
|
});
|
2014-03-09 16:58:32 -05:00
|
|
|
rx
|
2013-11-21 21:20:48 -06:00
|
|
|
});
|
2012-10-01 17:41:21 -05:00
|
|
|
|
|
|
|
// Wait on each port, accumulating the results
|
2014-03-09 16:58:32 -05:00
|
|
|
let result = rxs.iter().fold(0, |accum, rx| accum + rx.recv() );
|
2012-10-01 17:41:21 -05:00
|
|
|
# fn some_expensive_computation(_i: uint) -> int { 42 }
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2012-10-01 17:41:21 -05:00
|
|
|
|
2013-05-26 12:10:16 -05:00
|
|
|
## Backgrounding computations: Futures
|
2014-08-25 20:15:20 -05:00
|
|
|
|
|
|
|
With `sync::Future`, rust has a mechanism for requesting a computation and
|
|
|
|
getting the result later.
|
2013-05-17 16:11:49 -05:00
|
|
|
|
|
|
|
The basic example below illustrates this.
|
2014-01-03 12:17:19 -06:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-12-29 17:03:01 -06:00
|
|
|
# #![allow(deprecated)]
|
2014-06-07 13:13:26 -05:00
|
|
|
use std::sync::Future;
|
2014-01-30 14:04:47 -06:00
|
|
|
|
|
|
|
# fn main() {
|
2013-05-17 16:11:49 -05:00
|
|
|
# fn make_a_sandwich() {};
|
2013-10-27 13:59:58 -05:00
|
|
|
fn fib(n: u64) -> u64 {
|
2013-05-17 16:11:49 -05:00
|
|
|
// lengthy computation returning an uint
|
|
|
|
12586269025
|
|
|
|
}
|
|
|
|
|
2014-11-26 07:12:18 -06:00
|
|
|
let mut delayed_fib = Future::spawn(move || fib(50));
|
2013-05-17 16:11:49 -05:00
|
|
|
make_a_sandwich();
|
2014-05-22 13:28:01 -05:00
|
|
|
println!("fib(50) = {}", delayed_fib.get())
|
2014-01-30 14:04:47 -06:00
|
|
|
# }
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2013-05-17 16:11:49 -05:00
|
|
|
|
2014-10-11 14:55:36 -05:00
|
|
|
The call to `future::spawn` immediately returns a `future` object regardless of
|
2014-08-25 20:15:20 -05:00
|
|
|
how long it takes to run `fib(50)`. You can then make yourself a sandwich while
|
|
|
|
the computation of `fib` is running. The result of the execution of the method
|
|
|
|
is obtained by calling `get` on the future. This call will block until the
|
|
|
|
value is available (*i.e.* the computation is complete). Note that the future
|
|
|
|
needs to be mutable so that it can save the result for next time `get` is
|
|
|
|
called.
|
2013-05-17 16:11:49 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
Here is another example showing how futures allow you to background
|
|
|
|
computations. The workload will be distributed on the available cores.
|
2014-01-03 12:17:19 -06:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-12-29 17:03:01 -06:00
|
|
|
# #![allow(deprecated)]
|
2014-11-09 23:26:10 -06:00
|
|
|
# use std::num::Float;
|
2014-06-07 13:13:26 -05:00
|
|
|
# use std::sync::Future;
|
2013-05-17 16:11:49 -05:00
|
|
|
fn partial_sum(start: uint) -> f64 {
|
|
|
|
let mut local_sum = 0f64;
|
2013-08-03 11:45:23 -05:00
|
|
|
for num in range(start*100000, (start+1)*100000) {
|
2014-04-17 22:49:37 -05:00
|
|
|
local_sum += (num as f64 + 1.0).powf(-2.0);
|
2013-05-17 16:11:49 -05:00
|
|
|
}
|
|
|
|
local_sum
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2014-11-26 07:12:18 -06:00
|
|
|
let mut futures = Vec::from_fn(200, |ind| Future::spawn(move || partial_sum(ind)));
|
2013-05-17 16:11:49 -05:00
|
|
|
|
|
|
|
let mut final_res = 0f64;
|
2014-09-14 22:27:36 -05:00
|
|
|
for ft in futures.iter_mut() {
|
2013-05-17 16:11:49 -05:00
|
|
|
final_res += ft.get();
|
|
|
|
}
|
2013-09-30 12:32:28 -05:00
|
|
|
println!("π^2/6 is not far from : {}", final_res);
|
2013-05-17 16:11:49 -05:00
|
|
|
}
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2013-05-17 16:11:49 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
## Sharing without copying: Arc
|
2013-05-26 12:10:16 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
To share data between threads, a first approach would be to only use channel as
|
2014-08-25 20:15:20 -05:00
|
|
|
we have seen previously. A copy of the data to share would then be made for
|
2014-12-26 15:04:27 -06:00
|
|
|
each thread. In some cases, this would add up to a significant amount of wasted
|
2014-08-25 20:15:20 -05:00
|
|
|
memory and would require copying the same data more than necessary.
|
2013-05-26 12:10:16 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
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
|
2014-12-26 15:04:27 -06:00
|
|
|
will no longer be copied for each thread. The Arc acts as a reference to the
|
2014-08-25 20:15:20 -05:00
|
|
|
shared data and only this reference is shared and cloned.
|
2013-05-26 12:10:16 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
Here is a small example showing how to use Arcs. We wish to run concurrently
|
2014-12-26 15:04:27 -06:00
|
|
|
several computations on a single large vector of floats. Each thread needs the
|
2014-08-25 20:15:20 -05:00
|
|
|
full vector to perform its duty.
|
2014-01-03 12:17:19 -06:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-11-09 23:26:10 -06:00
|
|
|
use std::num::Float;
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 03:39:37 -05:00
|
|
|
use std::rand;
|
2014-06-07 13:13:26 -05:00
|
|
|
use std::sync::Arc;
|
2013-05-26 12:10:16 -05:00
|
|
|
|
2014-04-17 17:59:07 -05:00
|
|
|
fn pnorm(nums: &[f64], p: uint) -> f64 {
|
2014-04-17 22:49:37 -05:00
|
|
|
nums.iter().fold(0.0, |a, b| a + b.powf(p as f64)).powf(1.0 / (p as f64))
|
2013-05-26 12:10:16 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2014-04-17 17:59:07 -05:00
|
|
|
let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
|
2013-07-22 15:57:40 -05:00
|
|
|
let numbers_arc = Arc::new(numbers);
|
2013-05-26 12:10:16 -05:00
|
|
|
|
2013-08-03 11:45:23 -05:00
|
|
|
for num in range(1u, 10) {
|
2014-12-26 15:04:27 -06:00
|
|
|
let thread_numbers = numbers_arc.clone();
|
2013-05-26 12:10:16 -05:00
|
|
|
|
2014-11-26 07:12:18 -06:00
|
|
|
spawn(move || {
|
2014-12-26 15:04:27 -06:00
|
|
|
println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
|
2014-01-27 23:53:01 -06:00
|
|
|
});
|
2013-05-26 12:10:16 -05:00
|
|
|
}
|
|
|
|
}
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2013-05-26 12:10:16 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
The function `pnorm` performs a simple computation on the vector (it computes
|
|
|
|
the sum of its items at the power given as argument and takes the inverse power
|
|
|
|
of this value). The Arc on the vector is created by the line:
|
2014-01-03 12:17:19 -06:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 03:39:37 -05:00
|
|
|
# use std::rand;
|
2014-06-07 13:13:26 -05:00
|
|
|
# use std::sync::Arc;
|
2014-01-30 14:04:47 -06:00
|
|
|
# fn main() {
|
2014-04-17 17:59:07 -05:00
|
|
|
# let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
|
2014-08-19 18:34:41 -05:00
|
|
|
let numbers_arc = Arc::new(numbers);
|
2014-01-30 14:04:47 -06:00
|
|
|
# }
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2014-01-03 12:17:19 -06:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
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
|
2014-08-25 20:15:20 -05:00
|
|
|
Arc reference can be used as a shared reference to the underlying vector as
|
|
|
|
if it were local.
|
2014-01-03 12:17:19 -06:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 03:39:37 -05:00
|
|
|
# use std::rand;
|
2014-06-07 13:13:26 -05:00
|
|
|
# use std::sync::Arc;
|
2014-05-15 17:31:28 -05:00
|
|
|
# fn pnorm(nums: &[f64], p: uint) -> f64 { 4.0 }
|
2014-01-30 14:04:47 -06:00
|
|
|
# fn main() {
|
2014-04-17 17:59:07 -05:00
|
|
|
# let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
|
2013-07-22 15:57:40 -05:00
|
|
|
# let numbers_arc = Arc::new(numbers);
|
2014-05-15 17:31:28 -05:00
|
|
|
# let num = 4;
|
2014-12-26 15:04:27 -06:00
|
|
|
let thread_numbers = numbers_arc.clone();
|
2014-11-26 07:12:18 -06:00
|
|
|
spawn(move || {
|
2014-12-26 15:04:27 -06:00
|
|
|
// Capture thread_numbers and use it as if it was the underlying vector
|
|
|
|
println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
|
2014-05-15 17:31:28 -05:00
|
|
|
});
|
2014-01-30 14:04:47 -06:00
|
|
|
# }
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2013-05-26 12:10:16 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
# Handling thread panics
|
2012-10-01 20:42:11 -05:00
|
|
|
|
2014-10-09 14:17:22 -05:00
|
|
|
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
|
2014-12-26 15:04:27 -06:00
|
|
|
boolean expression is false) are both ways to raise exceptions. When a thread
|
|
|
|
raises an exception, the thread unwinds its stack—running destructors and
|
2014-10-11 14:55:36 -05:00
|
|
|
freeing memory along the way—and then exits. Unlike exceptions in C++,
|
2014-12-26 15:04:27 -06:00
|
|
|
exceptions in Rust are unrecoverable within a single thread: once a thread panics,
|
2012-10-09 18:14:55 -05:00
|
|
|
there is no way to "catch" the exception.
|
2012-10-01 20:42:11 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
While it isn't possible for a thread to recover from panicking, threads may notify
|
2014-10-09 14:17:22 -05:00
|
|
|
each other if they panic. The simplest way of handling a panic is with the
|
2014-10-11 14:55:36 -05:00
|
|
|
`try` function, which is similar to `spawn`, but immediately blocks and waits
|
2014-12-26 15:04:27 -06:00
|
|
|
for the child thread to finish. `try` returns a value of type
|
2014-10-11 14:55:36 -05:00
|
|
|
`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`
|
|
|
|
result with an `int` field (representing a successful result) or an `Err` result
|
|
|
|
(representing termination with an error).
|
2012-10-01 20:42:11 -05:00
|
|
|
|
2014-12-14 02:05:32 -06:00
|
|
|
```{rust,ignore}
|
2014-12-06 20:34:37 -06:00
|
|
|
# use std::thread::Thread;
|
2012-10-01 20:42:11 -05:00
|
|
|
# fn some_condition() -> bool { false }
|
|
|
|
# fn calculate_result() -> int { 0 }
|
2014-12-14 02:05:32 -06:00
|
|
|
let result: Result<int, Box<std::any::Any + Send>> = Thread::spawn(move || {
|
2012-10-01 20:42:11 -05:00
|
|
|
if some_condition() {
|
|
|
|
calculate_result()
|
|
|
|
} else {
|
2014-10-09 14:17:22 -05:00
|
|
|
panic!("oops!");
|
2012-10-01 20:42:11 -05:00
|
|
|
}
|
2014-12-06 20:34:37 -06:00
|
|
|
}).join();
|
2013-03-28 20:39:09 -05:00
|
|
|
assert!(result.is_err());
|
2014-08-25 20:15:20 -05:00
|
|
|
```
|
2012-10-01 20:42:11 -05:00
|
|
|
|
2014-08-25 20:15:20 -05:00
|
|
|
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
|
2014-12-26 15:04:27 -06:00
|
|
|
child thread terminates successfully, `try` will return an `Ok` result; if the
|
|
|
|
child thread panics, `try` will return an `Error` result.
|
2012-10-01 20:42:11 -05:00
|
|
|
|
2015-01-08 12:27:03 -06:00
|
|
|
[`Result`]: ../std/result/index.html
|
2012-10-01 20:42:11 -05:00
|
|
|
|
2014-12-26 15:04:27 -06:00
|
|
|
> *Note:* A panicked thread does not currently produce a useful error
|
2012-10-09 18:14:55 -05:00
|
|
|
> value (`try` always returns `Err(())`). In the
|
2014-12-26 15:04:27 -06:00
|
|
|
> future, it may be possible for threads to intercept the value passed to
|
2014-10-09 14:17:22 -05:00
|
|
|
> `panic!()`.
|
2012-10-01 20:42:11 -05:00
|
|
|
|
2014-10-09 14:17:22 -05:00
|
|
|
But not all panics are created equal. In some cases you might need to abort
|
2014-08-25 20:15:20 -05:00
|
|
|
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
|
2014-10-09 14:17:22 -05:00
|
|
|
contain the panic at a certain boundary (perhaps a small piece of input from
|
2014-08-25 20:15:20 -05:00
|
|
|
the outside world, which you happen to be processing in parallel, is malformed
|
2014-12-26 15:04:27 -06:00
|
|
|
such that the processing thread cannot proceed).
|