Complete thread1 and thread2
This commit is contained in:
@@ -8,8 +8,6 @@
|
|||||||
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
|||||||
@@ -7,9 +7,7 @@
|
|||||||
// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@@ -19,7 +17,7 @@ struct JobStatus {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// TODO: `Arc` isn't enough if you want a **mutable** shared state
|
// 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![];
|
let mut handles = vec![];
|
||||||
for _ in 0..10 {
|
for _ in 0..10 {
|
||||||
@@ -27,7 +25,8 @@ fn main() {
|
|||||||
let handle = thread::spawn(move || {
|
let handle = thread::spawn(move || {
|
||||||
thread::sleep(Duration::from_millis(250));
|
thread::sleep(Duration::from_millis(250));
|
||||||
// TODO: You must take an action before you update a shared value
|
// 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);
|
handles.push(handle);
|
||||||
}
|
}
|
||||||
@@ -38,5 +37,5 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Print the value of `JobStatus.jobs_completed`
|
// TODO: Print the value of `JobStatus.jobs_completed`
|
||||||
println!("Jobs completed: {}", ???);
|
println!("Jobs completed: {}", status.lock().unwrap().jobs_completed);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user