-
Notifications
You must be signed in to change notification settings - Fork 125
/
s3_guard.rs
72 lines (62 loc) · 1.66 KB
/
s3_guard.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
use std::ops::{Deref, DerefMut};
use std::cell::UnsafeCell;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::{Acquire, Release};
pub struct SpinLock<T> {
locked: AtomicBool,
value: UnsafeCell<T>,
}
unsafe impl<T> Sync for SpinLock<T> where T: Send {}
pub struct Guard<'a, T> {
lock: &'a SpinLock<T>,
}
unsafe impl<T> Sync for Guard<'_, T> where T: Sync {}
impl<T> SpinLock<T> {
pub const fn new(value: T) -> Self {
Self {
locked: AtomicBool::new(false),
value: UnsafeCell::new(value),
}
}
pub fn lock(&self) -> Guard<T> {
while self.locked.swap(true, Acquire) {
std::hint::spin_loop();
}
Guard { lock: self }
}
}
impl<T> Deref for Guard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
// Safety: The very existence of this Guard
// guarantees we've exclusively locked the lock.
unsafe { &*self.lock.value.get() }
}
}
impl<T> DerefMut for Guard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
// Safety: The very existence of this Guard
// guarantees we've exclusively locked the lock.
unsafe { &mut *self.lock.value.get() }
}
}
impl<T> Drop for Guard<'_, T> {
fn drop(&mut self) {
self.lock.locked.store(false, Release);
}
}
#[test]
fn main() {
use std::thread;
let x = SpinLock::new(Vec::new());
thread::scope(|s| {
s.spawn(|| x.lock().push(1));
s.spawn(|| {
let mut g = x.lock();
g.push(2);
g.push(2);
});
});
let g = x.lock();
assert!(g.as_slice() == [1, 2, 2] || g.as_slice() == [2, 2, 1]);
}