From 726f5b0b645cfa2a4f3c924e8098c6a8478758b3 Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Wed, 23 Oct 2024 12:16:14 +0200 Subject: [PATCH] Exercise 07-04 --- exercises/07_threads/04_scoped_threads/src/lib.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/exercises/07_threads/04_scoped_threads/src/lib.rs b/exercises/07_threads/04_scoped_threads/src/lib.rs index d81a3a9..57c2cfe 100644 --- a/exercises/07_threads/04_scoped_threads/src/lib.rs +++ b/exercises/07_threads/04_scoped_threads/src/lib.rs @@ -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 { - todo!() + let (s1, s2) = v.split_at(v.len() / 2 as usize); + + thread::scope(|scope| { + let h1 = scope.spawn(|| s1.iter().sum::()); + let h2 = scope.spawn(|| s2.iter().sum::()); + h1.join().unwrap() + h2.join().unwrap() + }) } #[cfg(test)] -- 2.45.2