Skip to content

Commit 2a360c0

Browse files
committed
// threads2.rs
// // Building on the last exercise, we want all of the threads to complete their // work but this time the spawned threads need to be in charge of updating a // shared value: JobStatus.jobs_completed // // Execute `rustlings hint threads2` or use the `hint` watch subcommand for a // hint. // I AM NOT DONE use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; struct JobStatus { jobs_completed: u32, } fn main() { // 使用 Arc 实现共享所有权,Mutex 保证互斥访问 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)); // 锁定 Mutex 以获取对内部数据的访问权 let mut status = status_shared.lock().unwrap(); status.jobs_completed += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); // 锁定 Mutex 以读取当前完成的任务数 let status = status.lock().unwrap(); println!("jobs completed {}", status.jobs_completed); } }
1 parent 759f3ba commit 2a360c0

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

exercises/threads/threads2.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
// I AM NOT DONE
1111

12-
use std::sync::Arc;
12+
use std::sync::{Arc, Mutex};
1313
use std::thread;
1414
use std::time::Duration;
1515

@@ -18,22 +18,25 @@ struct JobStatus {
1818
}
1919

2020
fn main() {
21-
let status = Arc::new(JobStatus { jobs_completed: 0 });
21+
// 使用 Arc 实现共享所有权,Mutex 保证互斥访问
22+
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
2223
let mut handles = vec![];
24+
2325
for _ in 0..10 {
2426
let status_shared = Arc::clone(&status);
2527
let handle = thread::spawn(move || {
2628
thread::sleep(Duration::from_millis(250));
27-
// TODO: You must take an action before you update a shared value
28-
status_shared.jobs_completed += 1;
29+
// 锁定 Mutex 以获取对内部数据的访问权
30+
let mut status = status_shared.lock().unwrap();
31+
status.jobs_completed += 1;
2932
});
3033
handles.push(handle);
3134
}
35+
3236
for handle in handles {
3337
handle.join().unwrap();
34-
// TODO: Print the value of the JobStatus.jobs_completed. Did you notice
35-
// anything interesting in the output? Do you have to 'join' on all the
36-
// handles?
37-
println!("jobs completed {}", ???);
38+
// 锁定 Mutex 以读取当前完成的任务数
39+
let status = status.lock().unwrap();
40+
println!("jobs completed {}", status.jobs_completed);
3841
}
3942
}

0 commit comments

Comments
 (0)