Complete thread1 and thread2

This commit is contained in:
Dylan Smith
2024-04-19 16:18:07 -04:00
parent f222629213
commit 7c3575e6ac
2 changed files with 5 additions and 8 deletions

View File

@@ -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};

View File

@@ -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;
@@ -19,7 +17,7 @@ struct JobStatus {
fn main() {
// TODO: `Arc` isn't enough if you want a **mutable** shared state
let status = Arc::new(JobStatus { jobs_completed: 0 });
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let mut handles = vec![];
for _ in 0..10 {
@@ -27,7 +25,8 @@ fn main() {
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;
let mut s = status_shared.lock().unwrap();
s.jobs_completed += 1;
});
handles.push(handle);
}
@@ -38,5 +37,5 @@ fn main() {
}
// TODO: Print the value of `JobStatus.jobs_completed`
println!("Jobs completed: {}", ???);
println!("Jobs completed: {}", status.lock().unwrap().jobs_completed);
}