study_example/concurrency/
dead_lock.rs1use std::sync::{Arc, Mutex, MutexGuard};
2use std::thread;
3use std::time::Duration;
4
5fn dead_lock_create() {
12 let counter = Arc::new(Mutex::new(100));
13 let counter_b = Arc::new(Mutex::new(200));
14 let mut handles = vec![];
15 let counter_clone1 = counter.clone();
16 let counter_clone_b = counter_b.clone();
17 let handle1 = thread::spawn(move || {
18 let mut num = counter_clone1.lock().unwrap();
19 *num += 10;
20 println!("thread1 handle counter num {}", num);
21 thread::sleep(Duration::from_secs(1));
22 let mut num_b = counter_clone_b.lock().unwrap();
23 *num_b += 40;
24 println!("thread1 handle counter num_b {}", num_b);
25 });
26 handles.push(handle1);
27 let counter_clone2 = counter.clone();
28 let counter_clone2_b = counter_b.clone();
29 let handle2 = thread::spawn(move || {
31 let mut num_b = counter_clone2_b.lock().unwrap();
32 *num_b += 60;
33 thread::sleep(Duration::from_secs(1));
34 println!("thread2 handle counter num_b {}", num_b);
35 let mut num = counter_clone2.lock().unwrap();
36 *num += 20;
37 println!("thread2 handle counter num {}", num);
38 });
39 handles.push(handle2);
40 for handle in handles {
41 handle.join().unwrap();
42 }
43 println!("result: {}", *counter.lock().unwrap());
44}
45
46pub fn dead_lock_study() {
47 dead_lock_create();
48}