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
use core::sync::atomic::{self, AtomicUsize, Ordering};
use Backoff;
pub struct SeqLock {
state: AtomicUsize,
}
impl SeqLock {
pub const INIT: Self = Self {
state: AtomicUsize::new(0),
};
#[inline]
pub fn optimistic_read(&self) -> Option<usize> {
let state = self.state.load(Ordering::Acquire);
if state == 1 {
None
} else {
Some(state)
}
}
#[inline]
pub fn validate_read(&self, stamp: usize) -> bool {
atomic::fence(Ordering::Acquire);
self.state.load(Ordering::Relaxed) == stamp
}
#[inline]
pub fn write(&'static self) -> SeqLockWriteGuard {
let backoff = Backoff::new();
loop {
let previous = self.state.swap(1, Ordering::Acquire);
if previous != 1 {
atomic::fence(Ordering::Release);
return SeqLockWriteGuard {
lock: self,
state: previous,
};
}
backoff.snooze();
}
}
}
pub struct SeqLockWriteGuard {
lock: &'static SeqLock,
state: usize,
}
impl SeqLockWriteGuard {
#[inline]
pub fn abort(self) {
self.lock.state.store(self.state, Ordering::Release);
}
}
impl Drop for SeqLockWriteGuard {
#[inline]
fn drop(&mut self) {
self.lock
.state
.store(self.state.wrapping_add(2), Ordering::Release);
}
}