Update crossbeam-spawn.md (#496)

* Update crossbeam-spawn.md

In the latest version od Crossbeam ([docs](https://docs.rs/crossbeam/0.5.0/crossbeam/)) we have two changes:

1. Spawned closures take an argument of type `&Scope` which can be used for nested spawns.
2. The `scope` function returns a `Result` indicating whether spawned threads have been joined with success or not.

Updating the example accordingly.

* Return option from find_max

* Use split_at
This commit is contained in:
Stjepan Glavina 2018-12-08 02:51:26 +00:00 committed by Andrew Gauger
parent c786f03e92
commit c1d3f12ef4
2 changed files with 20 additions and 18 deletions

View file

@ -14,7 +14,7 @@ byteorder = "1.0"
cc = "1.0"
chrono = "0.4"
clap = "2.29"
crossbeam = "0.4"
crossbeam = "0.5"
csv = "1.0"
data-encoding = "2.1.0"
env_logger = "0.5"

View file

@ -12,29 +12,31 @@ This example splits the array in half and performs the work in separate threads.
```rust
extern crate crossbeam;
use std::cmp;
fn main() {
let arr = &[-4, 1, 10, 25];
let max = find_max(arr, 0, arr.len());
assert_eq!(25, max);
let arr = &[1, 25, -4, 10];
let max = find_max(arr);
assert_eq!(max, Some(25));
}
fn find_max(arr: &[i32], start: usize, end: usize) -> i32 {
fn find_max(arr: &[i32]) -> Option<i32> {
const THRESHOLD: usize = 2;
if end - start <= THRESHOLD {
return *arr.iter().max().unwrap();
if arr.len() <= THRESHOLD {
return arr.iter().cloned().max();
}
let mid = start + (end - start) / 2;
crossbeam::thread::scope(|scope| {
let left = scope.spawn(|| find_max(arr, start, mid));
let right = scope.spawn(|| find_max(arr, mid, end));
// NOTE(unwrap): `join` will return an error if the thread panicked.
// This way, panics will be propagated up to the `scope` call
cmp::max(left.join().unwrap(), right.join().unwrap())
})
let mid = arr.len() / 2;
let (left, right) = arr.split_at(mid);
crossbeam::scope(|s| {
let thread_l = s.spawn(|_| find_max(left));
let thread_r = s.spawn(|_| find_max(right));
let min_l = thread_l.join().unwrap()?;
let min_r = thread_r.join().unwrap()?;
Some(min_l.max(min_r))
}).unwrap()
}
```