2018-02-22 00:09:53 -06:00
|
|
|
// arc1.rs
|
2021-04-21 07:50:03 -05:00
|
|
|
// In this exercise, we are given a Vec of u32 called "numbers" with values ranging
|
|
|
|
// from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ]
|
|
|
|
// We would like to use this set of numbers within 8 different threads simultaneously.
|
|
|
|
// Each thread is going to get the sum of every eighth value, with an offset.
|
|
|
|
// The first thread (offset 0), will sum 0, 8, 16, ...
|
|
|
|
// The second thread (offset 1), will sum 1, 9, 17, ...
|
|
|
|
// The third thread (offset 2), will sum 2, 10, 18, ...
|
|
|
|
// ...
|
|
|
|
// The eighth thread (offset 7), will sum 7, 15, 23, ...
|
|
|
|
|
|
|
|
// Because we are using threads, our values need to be thread-safe. Therefore,
|
|
|
|
// we are using Arc. We need to make a change in each of the two TODOs.
|
|
|
|
|
|
|
|
|
2015-09-30 20:08:35 -05:00
|
|
|
// Make this code compile by filling in a value for `shared_numbers` where the
|
2021-04-21 07:50:03 -05:00
|
|
|
// first TODO comment is, and create an initial binding for `child_numbers`
|
|
|
|
// where the second TODO comment is. Try not to create any copies of the `numbers` Vec!
|
2022-07-14 11:17:23 -05:00
|
|
|
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.
|
2015-09-28 08:43:11 -05:00
|
|
|
|
2020-06-14 05:15:35 -05:00
|
|
|
#![forbid(unused_imports)] // Do not change this, (or the next) line.
|
2015-09-28 08:43:11 -05:00
|
|
|
use std::sync::Arc;
|
|
|
|
use std::thread;
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let numbers: Vec<_> = (0..100u32).collect();
|
2023-03-24 16:18:51 -05:00
|
|
|
let shared_numbers = Arc::new(numbers);
|
2015-09-28 08:43:11 -05:00
|
|
|
let mut joinhandles = Vec::new();
|
|
|
|
|
2015-09-30 20:08:35 -05:00
|
|
|
for offset in 0..8 {
|
2023-03-24 16:18:51 -05:00
|
|
|
let child_numbers = Arc::clone(&shared_numbers);
|
2019-06-06 21:52:42 -05:00
|
|
|
joinhandles.push(thread::spawn(move || {
|
2022-04-19 10:11:27 -05:00
|
|
|
let sum: u32 = child_numbers.iter().filter(|n| *n % 8 == offset).sum();
|
2015-09-28 08:43:11 -05:00
|
|
|
println!("Sum of offset {} is {}", offset, sum);
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
for handle in joinhandles.into_iter() {
|
|
|
|
handle.join().unwrap();
|
|
|
|
}
|
|
|
|
}
|