Exercise 07-04
authorGreg Burri <greg.burri@gmail.com>
Wed, 23 Oct 2024 10:16:14 +0000 (12:16 +0200)
committerGreg Burri <greg.burri@gmail.com>
Wed, 23 Oct 2024 10:16:14 +0000 (12:16 +0200)
exercises/07_threads/04_scoped_threads/src/lib.rs

index d81a3a9..57c2cfe 100644 (file)
@@ -2,8 +2,16 @@
 //  and compute the sum of each half in a separate thread.
 //  Don't perform any heap allocation. Don't leak any memory.
 
+use std::thread;
+
 pub fn sum(v: Vec<i32>) -> i32 {
-    todo!()
+    let (s1, s2) = v.split_at(v.len() / 2 as usize);
+
+    thread::scope(|scope| {
+        let h1 = scope.spawn(|| s1.iter().sum::<i32>());
+        let h2 = scope.spawn(|| s2.iter().sum::<i32>());
+        h1.join().unwrap() + h2.join().unwrap()
+    })
 }
 
 #[cfg(test)]