study_example/concurrency/
mutex_shared_state.rs

1use std::sync::Arc;
2use std::sync::Mutex;
3use std::thread;
4
5/// 运行结果如下
6/// ```txt
7/// m: Mutex { data: 8, poisoned: false, .. }
8/// ```
9fn mutex_api_usage() {
10    let m = Mutex::new(42);
11    {
12        let mut num = m.lock().unwrap();
13        *num = 8;
14    }
15    println!("m: {:?}", m);
16}
17
18/// 运行结果如下
19/// ```txt
20/// result: 10
21/// ```
22fn share_mutex_in_multi_thread() {
23    let counter = Arc::new(Mutex::new(0));
24    let mut handles = vec![];
25    for _ in 0..10 {
26        let counter_clone = Arc::clone(&counter);
27        let handle = thread::spawn(move || {
28            let mut num = counter_clone.lock().unwrap();
29            *num += 1;
30        });
31        handles.push(handle);
32    }
33    for handle in handles {
34        handle.join().unwrap();
35    }
36    println!("result: {}", *counter.lock().unwrap());
37}
38
39pub fn mutex_shared_state_study() {
40    mutex_api_usage();
41    share_mutex_in_multi_thread();
42}