rustlings

solving rustlings ft. dracuxan
git clone [email protected]:dracuxan/rustlings.git
Log | Files | Refs

arc1.rs (1514B)


      1 // In this exercise, we are given a `Vec` of `u32` called `numbers` with values
      2 // ranging from 0 to 99. We would like to use this set of numbers within 8
      3 // different threads simultaneously. Each thread is going to get the sum of
      4 // every eighth value with an offset.
      5 //
      6 // The first thread (offset 0), will sum 0, 8, 16, …
      7 // The second thread (offset 1), will sum 1, 9, 17, …
      8 // The third thread (offset 2), will sum 2, 10, 18, …
      9 // …
     10 // The eighth thread (offset 7), will sum 7, 15, 23, …
     11 //
     12 // Each thread should own a reference-counting pointer to the vector of
     13 // numbers. But `Rc` isn't thread-safe. Therefore, we need to use `Arc`.
     14 //
     15 // Don't get distracted by how threads are spawned and joined. We will practice
     16 // that later in the exercises about threads.
     17 
     18 // Don't change the lines below.
     19 #![forbid(unused_imports)]
     20 use std::{sync::Arc, thread};
     21 
     22 fn main() {
     23     let numbers: Vec<_> = (0..100u32).collect();
     24 
     25     // TODO: Define `shared_numbers` by using `Arc`.
     26     // let shared_numbers = ???;
     27 
     28     let mut join_handles = Vec::new();
     29 
     30     for offset in 0..8 {
     31         // TODO: Define `child_numbers` using `shared_numbers`.
     32         // let child_numbers = ???;
     33 
     34         let handle = thread::spawn(move || {
     35             let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();
     36             println!("Sum of offset {offset} is {sum}");
     37         });
     38 
     39         join_handles.push(handle);
     40     }
     41 
     42     for handle in join_handles.into_iter() {
     43         handle.join().unwrap();
     44     }
     45 }