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
use std::future::Future;
use std::sync::Arc;
use anyhow::Result;
use hashbrown::HashMap;
use tokio::sync::{Mutex, Notify};
#[derive(Clone)]
struct Call<T> {
nt: Arc<Notify>,
res: Arc<parking_lot::RwLock<Option<Arc<Result<T>>>>>,
}
impl<T> Call<T> {
fn new() -> Call<T> {
Call {
nt: Arc::new(Notify::new()),
res: Arc::new(parking_lot::RwLock::new(None)),
}
}
}
#[derive(Default)]
pub struct Group<T> {
m: Mutex<HashMap<String, Arc<Call<T>>>>,
}
impl<T> Group<T> {
pub fn new() -> Group<T> {
Group {
m: Mutex::new(HashMap::new()),
}
}
pub async fn work<Fut>(&self, key: &str, func: impl Fn() -> Fut) -> Arc<Result<T>>
where
Fut: Future<Output = Result<T>>,
{
let mut m = self.m.lock().await;
if let Some(c) = m.get(key) {
let c = c.clone();
let nt = c.nt.notified();
drop(m);
nt.await;
let res = c.res.read();
return Arc::clone(res.as_ref().unwrap());
}
let c = Arc::new(Call::new());
m.insert(key.to_owned(), c);
drop(m);
let res = Arc::new(func().await);
let mut m = self.m.lock().await;
let c = m.get(key).unwrap();
let mut m2 = c.res.write();
*m2 = Some(Arc::clone(&res));
drop(m2);
c.nt.notify_waiters();
m.remove(key).unwrap();
drop(m);
res
}
}
#[cfg(test)]
mod tests {
use super::Group;
use anyhow::Result;
const RES: usize = 7;
async fn return_res() -> Result<usize> {
Ok(7)
}
#[tokio::test]
async fn test_simple() {
let g = Group::new();
let res = g.work("key", return_res).await;
let r = res.as_ref().as_ref().unwrap();
assert_eq!(r.clone(), RES);
}
#[tokio::test]
async fn test_multiple_threads() {
use futures::future::join_all;
use std::sync::Arc;
use std::time::Duration;
async fn expensive_fn() -> Result<usize> {
tokio::time::sleep(Duration::new(1, 500)).await;
Ok(RES)
}
let g = Arc::new(Group::new());
let mut handlers = Vec::new();
for _ in 0..10 {
let g = g.clone();
handlers.push(tokio::spawn(async move {
let res = g.work("key", expensive_fn).await;
let r = res.as_ref().as_ref().unwrap();
println!("{}", r);
}));
}
join_all(handlers).await;
}
}