|
21 | 21 | // |
22 | 22 | // Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. |
23 | 23 |
|
24 | | -// I AM NOT DONE |
| 24 | +#![forbid(unused_imports)] // Do not change this, (or the next) line. |
| 25 | +use std::sync::Arc; |
| 26 | +use std::thread; |
| 27 | + |
| 28 | +fn main() { |
| 29 | + let numbers: Vec<_> = (0..100u32).collect(); |
| 30 | + let shared_numbers = Arc::new(numbers); |
| 31 | + let mut joinhandles = Vec::new(); |
| 32 | + |
| 33 | + for offset in 0..8 { |
| 34 | + let child_numbers = Arc::clone(&shared_numbers); |
| 35 | + joinhandles.push(thread::spawn(move || { |
| 36 | + let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); |
| 37 | + println!("Sum of offset {} is {}", offset, sum); |
| 38 | + })); |
| 39 | + } |
| 40 | + for handle in joinhandles.into_iter() { |
| 41 | + handle.join().unwrap(); |
| 42 | + } |
| 43 | +} |
| 44 | +// arc1.rs |
| 45 | +// |
| 46 | +// In this exercise, we are given a Vec of u32 called "numbers" with values |
| 47 | +// ranging from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ] We would like to use this |
| 48 | +// set of numbers within 8 different threads simultaneously. Each thread is |
| 49 | +// going to get the sum of every eighth value, with an offset. |
| 50 | +// |
| 51 | +// The first thread (offset 0), will sum 0, 8, 16, ... |
| 52 | +// The second thread (offset 1), will sum 1, 9, 17, ... |
| 53 | +// The third thread (offset 2), will sum 2, 10, 18, ... |
| 54 | +// ... |
| 55 | +// The eighth thread (offset 7), will sum 7, 15, 23, ... |
| 56 | +// |
| 57 | +// Because we are using threads, our values need to be thread-safe. Therefore, |
| 58 | +// we are using Arc. We need to make a change in each of the two TODOs. |
| 59 | +// |
| 60 | +// Make this code compile by filling in a value for `shared_numbers` where the |
| 61 | +// first TODO comment is, and create an initial binding for `child_numbers` |
| 62 | +// where the second TODO comment is. Try not to create any copies of the |
| 63 | +// `numbers` Vec! |
| 64 | +// |
| 65 | +// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. |
25 | 66 |
|
26 | 67 | #![forbid(unused_imports)] // Do not change this, (or the next) line. |
27 | 68 | use std::sync::Arc; |
28 | 69 | use std::thread; |
29 | 70 |
|
30 | 71 | fn main() { |
31 | 72 | let numbers: Vec<_> = (0..100u32).collect(); |
32 | | - let shared_numbers = // TODO |
| 73 | + let shared_numbers = Arc::new(numbers); |
33 | 74 | let mut joinhandles = Vec::new(); |
34 | 75 |
|
35 | 76 | for offset in 0..8 { |
36 | | - let child_numbers = // TODO |
| 77 | + let child_numbers = Arc::clone(&shared_numbers); |
37 | 78 | joinhandles.push(thread::spawn(move || { |
38 | 79 | let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); |
39 | 80 | println!("Sum of offset {} is {}", offset, sum); |
|
0 commit comments