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
use core::sync::atomic::{AtomicUsize, Ordering};
#[repr(C)]
pub struct Semaphore {
count: AtomicUsize,
mutex: bool,
}
extern "C" {
fn do_block(sem: *const Semaphore) -> usize;
}
impl Semaphore {
pub const fn new(start_count: usize) -> Semaphore {
Semaphore {
count: AtomicUsize::new(start_count),
mutex: false,
}
}
pub const fn new_mutex() -> Semaphore {
Semaphore {
count: AtomicUsize::new(1),
mutex: true,
}
}
pub fn is_available(&self) -> bool {
self.count.load(Ordering::Relaxed) > 0
}
pub fn take(&self) {
loop {
let old_val = self.count.load(Ordering::SeqCst);
if old_val == 0 {
unsafe {
do_block(self as *const Semaphore);
}
continue;
}
if self
.count
.compare_and_swap(old_val, old_val - 1, Ordering::SeqCst)
== old_val
{
break;
}
}
}
pub fn try_take(&self) -> bool {
let old_val = self.count.load(Ordering::SeqCst);
if old_val == 0 {
return false;
}
self.count
.compare_and_swap(old_val, old_val - 1, Ordering::SeqCst)
== old_val
}
pub fn give(&self) {
if self.mutex {
self.count.store(1, Ordering::SeqCst);
} else {
self.count.fetch_add(1, Ordering::SeqCst);
}
}
pub fn with_lock<F: FnMut()>(&self, mut f: F) {
self.take();
f();
self.give();
}
pub fn try_with_lock<F: FnMut()>(&self, mut f: F) -> bool {
if self.try_take() {
f();
self.give();
true
} else {
false
}
}
}