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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
|
use std::{
collections::HashMap,
future::Future,
pin::Pin,
sync::Mutex,
task::{Context, Poll, Waker},
};
use crate::{async_runtime::lock::MutexGuard, util::random_16};
/// CondVar is an async version of <https://doc.rust-lang.org/std/sync/struct.Condvar.html>
///
/// # Example
///
///```
/// use std::sync::Arc;
///
/// use karyon_core::async_util::CondVar;
/// use karyon_core::async_runtime::{spawn, lock::Mutex};
///
/// async {
///
/// let val = Arc::new(Mutex::new(false));
/// let condvar = Arc::new(CondVar::new());
///
/// let val_cloned = val.clone();
/// let condvar_cloned = condvar.clone();
/// spawn(async move {
/// let mut val = val_cloned.lock().await;
///
/// // While the boolean flag is false, wait for a signal.
/// while !*val {
/// val = condvar_cloned.wait(val).await;
/// }
///
/// // ...
/// });
///
/// let condvar_cloned = condvar.clone();
/// spawn(async move {
/// let mut val = val.lock().await;
///
/// // While the boolean flag is false, wait for a signal.
/// while !*val {
/// val = condvar_cloned.wait(val).await;
/// }
///
/// // ...
/// });
///
/// // Wake up all waiting tasks on this condvar
/// condvar.broadcast();
/// };
///
/// ```
pub struct CondVar {
inner: Mutex<Wakers>,
}
impl CondVar {
/// Creates a new CondVar
pub fn new() -> Self {
Self {
inner: Mutex::new(Wakers::new()),
}
}
/// Blocks the current task until this condition variable receives a notification.
pub async fn wait<'a, T>(&self, g: MutexGuard<'a, T>) -> MutexGuard<'a, T> {
#[cfg(feature = "smol")]
let m = MutexGuard::source(&g);
#[cfg(feature = "tokio")]
let m = MutexGuard::mutex(&g);
CondVarAwait::new(self, g).await;
m.lock().await
}
/// Wakes up one blocked task waiting on this condvar.
pub fn signal(&self) {
self.inner.lock().unwrap().wake(true);
}
/// Wakes up all blocked tasks waiting on this condvar.
pub fn broadcast(&self) {
self.inner.lock().unwrap().wake(false);
}
}
impl Default for CondVar {
fn default() -> Self {
Self::new()
}
}
struct CondVarAwait<'a, T> {
id: Option<u16>,
condvar: &'a CondVar,
guard: Option<MutexGuard<'a, T>>,
}
impl<'a, T> CondVarAwait<'a, T> {
fn new(condvar: &'a CondVar, guard: MutexGuard<'a, T>) -> Self {
Self {
condvar,
guard: Some(guard),
id: None,
}
}
}
impl<'a, T> Future for CondVarAwait<'a, T> {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut inner = self.condvar.inner.lock().unwrap();
match self.guard.take() {
Some(_) => {
// the first pooll will release the Mutexguard
self.id = Some(inner.put(Some(cx.waker().clone())));
Poll::Pending
}
None => {
// Return Ready if it has already been polled and removed
// from the waker list.
if self.id.is_none() {
return Poll::Ready(());
}
let i = self.id.as_ref().unwrap();
match inner.wakers.get_mut(i).unwrap() {
Some(wk) => {
// This will prevent cloning again
if !wk.will_wake(cx.waker()) {
wk.clone_from(cx.waker());
}
Poll::Pending
}
None => {
inner.delete(i);
self.id = None;
Poll::Ready(())
}
}
}
}
}
}
impl<'a, T> Drop for CondVarAwait<'a, T> {
fn drop(&mut self) {
if let Some(id) = self.id {
let mut inner = self.condvar.inner.lock().unwrap();
if let Some(wk) = inner.wakers.get_mut(&id).unwrap().take() {
wk.wake()
}
}
}
}
/// Wakers is a helper struct to store the task wakers
struct Wakers {
wakers: HashMap<u16, Option<Waker>>,
}
impl Wakers {
fn new() -> Self {
Self {
wakers: HashMap::new(),
}
}
fn put(&mut self, waker: Option<Waker>) -> u16 {
let mut id: u16;
id = random_16();
while self.wakers.contains_key(&id) {
id = random_16();
}
self.wakers.insert(id, waker);
id
}
fn delete(&mut self, id: &u16) -> Option<Option<Waker>> {
self.wakers.remove(id)
}
fn wake(&mut self, signal: bool) {
for (_, wk) in self.wakers.iter_mut() {
match wk.take() {
Some(w) => {
w.wake();
if signal {
break;
}
}
None => continue,
}
}
}
}
#[cfg(test)]
mod tests {
use std::{
collections::VecDeque,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
use crate::async_runtime::{block_on, lock::Mutex, spawn};
use super::*;
// The tests below demonstrate a solution to a problem in the Wikipedia
// explanation of condition variables:
// https://en.wikipedia.org/wiki/Monitor_(synchronization)#Solving_the_bounded_producer/consumer_problem.
struct Queue {
items: VecDeque<String>,
max_len: usize,
}
impl Queue {
fn new(max_len: usize) -> Self {
Self {
items: VecDeque::new(),
max_len,
}
}
fn is_full(&self) -> bool {
self.items.len() == self.max_len
}
fn is_empty(&self) -> bool {
self.items.is_empty()
}
}
#[test]
fn test_condvar_signal() {
block_on(async {
let number_of_tasks = 30;
let queue = Arc::new(Mutex::new(Queue::new(5)));
let condvar_full = Arc::new(CondVar::new());
let condvar_empty = Arc::new(CondVar::new());
let queue_cloned = queue.clone();
let condvar_full_cloned = condvar_full.clone();
let condvar_empty_cloned = condvar_empty.clone();
let _producer1 = spawn(async move {
for i in 1..number_of_tasks {
// Lock queue mtuex
let mut queue = queue_cloned.lock().await;
// Check if the queue is non-full
while queue.is_full() {
// Release queue mutex and sleep
queue = condvar_full_cloned.wait(queue).await;
}
queue.items.push_back(format!("task {i}"));
// Wake up the consumer
condvar_empty_cloned.signal();
}
});
let queue_cloned = queue.clone();
let task_consumed = Arc::new(AtomicUsize::new(0));
let task_consumed_ = task_consumed.clone();
let consumer = spawn(async move {
for _ in 1..number_of_tasks {
// Lock queue mtuex
let mut queue = queue_cloned.lock().await;
// Check if the queue is non-empty
while queue.is_empty() {
// Release queue mutex and sleep
queue = condvar_empty.wait(queue).await;
}
let _ = queue.items.pop_front().unwrap();
task_consumed_.fetch_add(1, Ordering::Relaxed);
// Do something
// Wake up the producer
condvar_full.signal();
}
});
let _ = consumer.await;
assert!(queue.lock().await.is_empty());
assert_eq!(task_consumed.load(Ordering::Relaxed), 29);
});
}
#[test]
fn test_condvar_broadcast() {
block_on(async {
let tasks = 30;
let queue = Arc::new(Mutex::new(Queue::new(5)));
let condvar = Arc::new(CondVar::new());
let queue_cloned = queue.clone();
let condvar_cloned = condvar.clone();
let _producer1 = spawn(async move {
for i in 1..tasks {
// Lock queue mtuex
let mut queue = queue_cloned.lock().await;
// Check if the queue is non-full
while queue.is_full() {
// Release queue mutex and sleep
queue = condvar_cloned.wait(queue).await;
}
queue.items.push_back(format!("producer1: task {i}"));
// Wake up all producer and consumer tasks
condvar_cloned.broadcast();
}
});
let queue_cloned = queue.clone();
let condvar_cloned = condvar.clone();
let _producer2 = spawn(async move {
for i in 1..tasks {
// Lock queue mtuex
let mut queue = queue_cloned.lock().await;
// Check if the queue is non-full
while queue.is_full() {
// Release queue mutex and sleep
queue = condvar_cloned.wait(queue).await;
}
queue.items.push_back(format!("producer2: task {i}"));
// Wake up all producer and consumer tasks
condvar_cloned.broadcast();
}
});
let queue_cloned = queue.clone();
let task_consumed = Arc::new(AtomicUsize::new(0));
let task_consumed_ = task_consumed.clone();
let consumer = spawn(async move {
for _ in 1..((tasks * 2) - 1) {
{
// Lock queue mutex
let mut queue = queue_cloned.lock().await;
// Check if the queue is non-empty
while queue.is_empty() {
// Release queue mutex and sleep
queue = condvar.wait(queue).await;
}
let _ = queue.items.pop_front().unwrap();
task_consumed_.fetch_add(1, Ordering::Relaxed);
// Do something
// Wake up all producer and consumer tasks
condvar.broadcast();
}
}
});
let _ = consumer.await;
assert!(queue.lock().await.is_empty());
assert_eq!(task_consumed.load(Ordering::Relaxed), 58);
});
}
}
|