-
Notifications
You must be signed in to change notification settings - Fork 122
/
mutex_3.rs
111 lines (96 loc) · 2.53 KB
/
mutex_3.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use atomic_wait::{wait, wake_one};
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};
pub struct Mutex<T> {
/// 0: unlocked
/// 1: locked, no other threads waiting
/// 2: locked, other threads waiting
state: AtomicU32,
value: UnsafeCell<T>,
}
unsafe impl<T> Sync for Mutex<T> where T: Send {}
pub struct MutexGuard<'a, T> {
pub(crate) mutex: &'a Mutex<T>,
}
unsafe impl<T> Sync for MutexGuard<'_, T> where T: Sync {}
impl<T> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.mutex.value.get() }
}
}
impl<T> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.mutex.value.get() }
}
}
impl<T> Mutex<T> {
pub const fn new(value: T) -> Self {
Self {
state: AtomicU32::new(0), // unlocked state
value: UnsafeCell::new(value),
}
}
pub fn lock(&self) -> MutexGuard<T> {
if self.state.compare_exchange(0, 1, Acquire, Relaxed).is_err() {
// The lock was already locked. :(
lock_contended(&self.state);
}
MutexGuard { mutex: self }
}
}
fn lock_contended(state: &AtomicU32) {
let mut spin_count = 0;
while state.load(Relaxed) == 1 && spin_count < 100 {
spin_count += 1;
std::hint::spin_loop();
}
if state.compare_exchange(0, 1, Acquire, Relaxed).is_ok() {
return;
}
while state.swap(2, Acquire) != 0 {
wait(state, 2);
}
}
impl<T> Drop for MutexGuard<'_, T> {
fn drop(&mut self) {
if self.mutex.state.swap(0, Release) == 2 {
wake_one(&self.mutex.state);
}
}
}
// TODO (bench)
#[test]
fn main() {
use std::time::Instant;
let m = Mutex::new(0);
std::hint::black_box(&m);
let start = Instant::now();
for _ in 0..5_000_000 {
*m.lock() += 1;
}
let duration = start.elapsed();
println!("locked {} times in {:?}", *m.lock(), duration);
}
// TODO (bench)
#[test]
fn main2() {
use std::thread;
use std::time::Instant;
let m = Mutex::new(0);
std::hint::black_box(&m);
let start = Instant::now();
thread::scope(|s| {
for _ in 0..4 {
s.spawn(|| {
for _ in 0..5_000_000 {
*m.lock() += 1;
}
});
}
});
let duration = start.elapsed();
println!("locked {} times in {:?}", *m.lock(), duration);
}