-
Notifications
You must be signed in to change notification settings - Fork 29
/
main.rs
94 lines (76 loc) · 2.7 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::Duration;
fn main() {
test_mutex();
test_rwlock();
demo_deadlock();
// demo_rwlock_upgrade(); // 由于标准库不支持锁升级,这部分代码作为说明用
}
fn test_mutex() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result from Mutex: {}", *counter.lock().unwrap());
}
fn test_rwlock() {
let data = Arc::new(RwLock::new(5));
let reader = Arc::clone(&data);
let writer = Arc::clone(&data);
let reader_thread = thread::spawn(move || {
let read_data = reader.read().unwrap();
println!("Reader got: {}", read_data);
});
let writer_thread = thread::spawn(move || {
let mut write_data = writer.write().unwrap();
*write_data += 1;
println!("Writer updated data to: {}", *write_data);
});
reader_thread.join().unwrap();
writer_thread.join().unwrap();
println!("Final result from RwLock: {}", *data.read().unwrap());
}
fn demo_deadlock() {
let resource_a = Arc::new(Mutex::new(42));
let resource_b = Arc::new(Mutex::new("Rust"));
let a_clone = Arc::clone(&resource_a);
let b_clone = Arc::clone(&resource_b);
let handle1 = thread::spawn(move || {
let a = resource_a.lock().unwrap();
thread::sleep(Duration::from_secs(1));
let b = resource_b.lock().unwrap();
println!("Thread 1 acquired resources: {} and {:?}", a, b);
});
let handle2 = thread::spawn(move || {
let b = b_clone.lock().unwrap();
thread::sleep(Duration::from_secs(1));
let a = a_clone.lock().unwrap();
println!("Thread 2 acquired resources: {} and {:?}", a, b);
});
handle1.join().unwrap();
handle2.join().unwrap();
}
// 此函数仅作解释用,实际Rust标准库不支持锁升级
// fn demo_rwlock_upgrade() {
// let lock = Arc::new(RwLock::new(1));
// let lock_clone = Arc::clone(&lock);
// let handle = thread::spawn(move || {
// let read_handle = lock.read().unwrap();
// println!("Read-lock acquired: {}", *read_handle);
// // 假设在此处需要锁升级
// let mut write_handle = lock.write().unwrap(); // 实际这里不能这样使用,会造成死锁
// *write_handle += 1;
// });
// handle.join().unwrap();
// println!("Value after supposed lock upgrade: {}", *lock.read().unwrap());
//}