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
104
105
106
107
108
109
110
111
112
113
114
115
use parking_lot::RwLock;
use std::future::Future;
use std::sync::Arc;
use tokio::sync::Notify;
pub struct ReverseSemaphorePermit(Arc<RwLock<Inner>>);
#[derive(Clone)]
pub struct ReverseSemaphore(Arc<RwLock<Inner>>);
impl Default for ReverseSemaphore {
fn default() -> Self {
Self::new()
}
}
impl ReverseSemaphore {
pub fn new() -> Self {
Self(Arc::new(RwLock::new(Inner {
n: Arc::new(Notify::new()),
c: 0,
})))
}
pub fn acquire(&self) -> ReverseSemaphorePermit {
ReverseSemaphorePermit::new(self.0.clone())
}
pub fn wait_on_zero_permits(&self) -> impl Future<Output = ()> + 'static + Send {
let inner = self.0.clone();
async move {
let n;
let fut;
{
let lock = inner.read();
if lock.c == 0 {
return;
}
n = lock.n.clone();
fut = n.notified();
drop(lock);
}
fut.await;
}
}
}
struct Inner {
n: Arc<Notify>,
c: usize,
}
impl ReverseSemaphorePermit {
fn new(inner: Arc<RwLock<Inner>>) -> Self {
inner.write().c += 1;
Self(inner)
}
}
impl Drop for ReverseSemaphorePermit {
fn drop(&mut self) {
let mut lock = self.0.write();
lock.c -= 1;
if lock.c == 0 {
lock.n.notify_waiters();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn test_reverse_semaphore() {
let rs = ReverseSemaphore::new();
let s = tokio::time::Instant::now();
rs.wait_on_zero_permits().await;
let es = s.elapsed().as_secs_f64();
assert!(es < 0.00015);
println!("zero wait, after {} s", es);
let s = tokio::time::Instant::now();
for t in 10..15 {
let permit = rs.acquire();
tokio::task::spawn(async move {
let _permit = permit;
tokio::time::sleep(std::time::Duration::from_millis(t)).await;
});
}
rs.wait_on_zero_permits().await;
let es = s.elapsed().as_secs_f64();
assert!(es > 0.00015);
println!("permit wait, after {} s", es);
}
}