2024-06-29 00:48:00 +01:00
|
|
|
// In this exercise, we are given a `Vec` of u32 called `numbers` with values
|
|
|
|
// ranging from 0 to 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.
|
2023-05-29 18:39:08 +01:00
|
|
|
//
|
2024-06-29 00:48:00 +01:00
|
|
|
// 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, …
|
2023-05-29 18:39:08 +01:00
|
|
|
//
|
2024-06-29 00:48:00 +01:00
|
|
|
// Because we are using threads, our values need to be thread-safe. Therefore,
|
|
|
|
// we are using `Arc`.
|
2015-09-28 14:43:11 +01:00
|
|
|
|
2024-06-29 00:48:00 +01:00
|
|
|
// Don't change the lines below.
|
|
|
|
#![forbid(unused_imports)]
|
|
|
|
use std::{sync::Arc, thread};
|
2015-09-28 14:43:11 +01:00
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let numbers: Vec<_> = (0..100u32).collect();
|
2024-06-29 00:48:00 +01:00
|
|
|
|
|
|
|
// TODO: Define `shared_numbers` by using `Arc`.
|
|
|
|
// let shared_numbers = ???;
|
|
|
|
|
|
|
|
let mut join_handles = Vec::new();
|
2015-09-28 14:43:11 +01:00
|
|
|
|
2015-10-01 02:08:35 +01:00
|
|
|
for offset in 0..8 {
|
2024-06-29 00:48:00 +01:00
|
|
|
// TODO: Define `child_numbers` using `shared_numbers`.
|
|
|
|
// let child_numbers = ???;
|
|
|
|
|
|
|
|
let handle = thread::spawn(move || {
|
2023-02-18 20:38:43 +00:00
|
|
|
let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();
|
2024-06-29 00:48:00 +01:00
|
|
|
println!("Sum of offset {offset} is {sum}");
|
|
|
|
});
|
|
|
|
|
|
|
|
join_handles.push(handle);
|
2015-09-28 14:43:11 +01:00
|
|
|
}
|
2024-06-29 00:48:00 +01:00
|
|
|
|
|
|
|
for handle in join_handles.into_iter() {
|
2015-09-28 14:43:11 +01:00
|
|
|
handle.join().unwrap();
|
|
|
|
}
|
|
|
|
}
|