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
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, Release};
static UNLOCKED: u32 = 0;
static LOCKED: u32 = 1;
pub struct NaiveMutex<T> {
state: AtomicU32,
value: UnsafeCell<T>,
}
unsafe impl<T> Sync for NaiveMutex<T> where T: Send {}
pub struct MutexGuard<'a, T> {
mutex: &'a NaiveMutex<T>,
}
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> Drop for MutexGuard<'_, T> {
#[inline]
fn drop(&mut self) {
self.mutex.state.store(UNLOCKED, Release);
wake_one(&self.mutex.state);
}
}
impl<T> NaiveMutex<T> {
pub fn new(value: T) -> Self {
Self {
state: AtomicU32::new(UNLOCKED),
value: UnsafeCell::new(value),
}
}
#[inline]
pub fn lock(&self) -> MutexGuard<T> {
while self.state.swap(LOCKED, Acquire) == LOCKED {
wait(&self.state, LOCKED);
}
MutexGuard { mutex: self }
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::thread::scope;
#[test]
fn test_mutex() {
let mutex = Arc::new(NaiveMutex::new(0));
scope(|s| {
for _ in 0..10 {
let mutex = mutex.clone();
s.spawn(move || {
for _ in 0..1000 {
let mut guard = mutex.lock();
*guard += 1;
}
});
}
});
assert_eq!(mutex.lock().deref(), &10000);
}
}