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
#[cfg(feature = "unstable")]
pub use dispatcher::*;
#[cfg(feature = "unstable")]
mod dispatcher {
use crate::task::spawn;
use async_trait::async_trait;
#[async_trait]
pub trait AsyncDispatcher: Sized + Send + 'static {
fn run(self) {
let ft = async move {
self.dispatch_loop().await;
};
spawn(ft);
}
async fn dispatch_loop(mut self);
}
#[cfg(test)]
mod test {
use std::time::Duration;
use async_lock::Lock;
use async_trait::async_trait;
use crate::test_async;
use crate::timer::sleep;
use super::*;
struct SimpleDispatcher {
count: Lock<u16>,
delay: Duration
}
#[async_trait]
impl AsyncDispatcher for SimpleDispatcher {
async fn dispatch_loop(mut self) {
use crate::timer::sleep;
let guard = self.count.lock().await;
let count = *guard;
drop(guard);
for _ in 0..count {
let mut guard = self.count.lock().await;
*guard = *guard - 1;
sleep(self.delay).await;
}
}
}
#[test_async]
async fn test_dispatcher() -> Result<(),()> {
let count = Lock::new(5);
let dispatcher = SimpleDispatcher { count: count.clone(), delay: Duration::from_micros(10) };
dispatcher.run();
sleep(Duration::from_millis(5)).await;
let guard = count.lock().await;
assert_eq!(*guard,0);
Ok(())
}
}
}