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
use core::{
cell::UnsafeCell,
hint,
marker::PhantomData,
ops::{Deref, DerefMut},
sync::atomic::{AtomicBool, Ordering},
};
pub struct Mutex<T> {
lock: AtomicBool,
cell: UnsafeCell<T>,
phantom: PhantomData<T>,
}
impl<T> Mutex<T> {
pub fn new(value: T) -> Self {
Self {
lock: AtomicBool::new(false),
cell: UnsafeCell::new(value),
phantom: PhantomData,
}
}
pub fn lock(&self) -> MutexGuard<T> {
while self
.lock
.compare_exchange(false, true, Ordering::Acquire, Ordering::Acquire)
.is_err()
{
while self.lock.load(Ordering::Relaxed) {
hint::spin_loop();
}
}
MutexGuard::new(self)
}
pub fn unlock(&self) {
self.lock.store(false, Ordering::Release);
}
}
unsafe impl<T> Sync for Mutex<T> {}
unsafe impl<T> Send for Mutex<T> {}
pub struct MutexGuard<'a, T> {
mutex: &'a Mutex<T>,
}
impl<'a, T> MutexGuard<'a, T> {
pub fn new(mutex: &'a Mutex<T>) -> Self {
Self { mutex }
}
}
impl<'a, T> Deref for MutexGuard<'a, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.mutex.cell.get() }
}
}
impl<'a, T> DerefMut for MutexGuard<'a, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.mutex.cell.get() }
}
}
impl<'a, T> Drop for MutexGuard<'a, T> {
fn drop(&mut self) {
self.mutex.unlock();
}
}