From 192f5509bb67900b4ca4523403de7348accad19c Mon Sep 17 00:00:00 2001 From: palutz <> Date: Thu, 21 Sep 2023 22:56:35 +0100 Subject: [PATCH] threads --- exercises/threads/threads1.rs | 5 +++-- exercises/threads/threads2.rs | 11 +++++------ exercises/threads/threads3.rs | 3 ++- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs index 80b6def3..e9f51ff4 100644 --- a/exercises/threads/threads1.rs +++ b/exercises/threads/threads1.rs @@ -8,8 +8,6 @@ // Execute `rustlings hint threads1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::thread; use std::time::{Duration, Instant}; @@ -27,6 +25,9 @@ fn main() { let mut results: Vec = vec![]; for handle in handles { // TODO: a struct is returned from thread::spawn, can you use it? + results.push( + handle.join().unwrap() + ); } if results.len() != 10 { diff --git a/exercises/threads/threads2.rs b/exercises/threads/threads2.rs index 62dad80d..64ee2c09 100644 --- a/exercises/threads/threads2.rs +++ b/exercises/threads/threads2.rs @@ -7,9 +7,7 @@ // Execute `rustlings hint threads2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; @@ -18,14 +16,15 @@ struct JobStatus { } fn main() { - let status = Arc::new(JobStatus { jobs_completed: 0 }); + // SOLUTION: added Mutex to manage the lock => Arc is an atomic reference to IMMUTABLE data + let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 })); let mut handles = vec![]; for _ in 0..10 { let status_shared = Arc::clone(&status); let handle = thread::spawn(move || { thread::sleep(Duration::from_millis(250)); // TODO: You must take an action before you update a shared value - status_shared.jobs_completed += 1; + status_shared.lock().unwrap().jobs_completed += 1; }); handles.push(handle); } @@ -34,6 +33,6 @@ fn main() { // TODO: Print the value of the JobStatus.jobs_completed. Did you notice // anything interesting in the output? Do you have to 'join' on all the // handles? - println!("jobs completed {}", ???); + println!("jobs completed {}", status.lock().unwrap().jobs_completed); } } diff --git a/exercises/threads/threads3.rs b/exercises/threads/threads3.rs index db7d41ba..d3450668 100644 --- a/exercises/threads/threads3.rs +++ b/exercises/threads/threads3.rs @@ -31,10 +31,11 @@ fn send_tx(q: Queue, tx: mpsc::Sender) -> () { let qc1 = Arc::clone(&qc); let qc2 = Arc::clone(&qc); + let tx1 = tx.clone(); thread::spawn(move || { for val in &qc1.first_half { println!("sending {:?}", val); - tx.send(*val).unwrap(); + tx1.send(*val).unwrap(); thread::sleep(Duration::from_secs(1)); } });