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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use futures_util::lock::Mutex;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
#[derive(Clone)]
pub struct WaitGroup {
inner: Arc<Inner>,
}
struct Inner {
count: Mutex<isize>,
waker: Mutex<Option<Waker>>,
}
impl WaitGroup {
pub fn new() -> WaitGroup {
WaitGroup {
inner: Arc::new(Inner {
count: Mutex::new(0),
waker: Mutex::new(None),
}),
}
}
pub async fn add(&mut self, delta: isize) {
if delta <= 0 {
panic!("The argument `delta` of wait group `add` must be a positive number");
}
let mut count = self.inner.count.lock().await;
*count += delta;
if *count >= isize::max_value() {
panic!("wait group count is too large");
}
}
pub async fn done(&mut self) {
let mut count = self.inner.count.lock().await;
*count -= 1;
if *count <= 0 {
if let Some(waker) = &*self.inner.waker.lock().await {
waker.clone().wake();
}
}
}
pub async fn count(&self) -> isize {
*self.inner.count.lock().await
}
}
impl Future for WaitGroup {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut count = self.inner.count.lock();
let pin_count = Pin::new(&mut count);
if let Poll::Ready(count) = pin_count.poll(cx) {
if *count <= 0 {
return Poll::Ready(());
}
}
let mut waker = self.inner.waker.lock();
let pin_waker = Pin::new(&mut waker);
if let Poll::Ready(mut waker) = pin_waker.poll(cx) {
*waker = Some(cx.waker().clone());
}
Poll::Pending
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
#[should_panic]
async fn add_zero() {
let mut wg = WaitGroup::new();
wg.add(0).await;
}
#[tokio::test]
#[should_panic]
async fn add_neg_one() {
let mut wg = WaitGroup::new();
wg.add(-1).await;
}
#[tokio::test]
#[should_panic]
async fn add_very_max() {
let mut wg = WaitGroup::new();
wg.add(isize::max_value()).await;
}
#[tokio::test]
async fn add() {
let mut wg = WaitGroup::new();
wg.add(1).await;
wg.add(10).await;
assert_eq!(*wg.inner.count.lock().await, 11);
}
#[tokio::test]
async fn done() {
let mut wg = WaitGroup::new();
wg.done().await;
wg.done().await;
assert_eq!(*wg.inner.count.lock().await, -2);
}
#[tokio::test]
async fn count() {
let mut wg = WaitGroup::new();
assert_eq!(wg.count().await, 0);
wg.add(10).await;
assert_eq!(wg.count().await, 10);
wg.done().await;
assert_eq!(wg.count().await, 9);
}
}