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
#![forbid(unsafe_code)]
use futures::future::{Future, FutureExt};
use std::sync::Arc;
use tokio::{
runtime::Handle,
sync::{OwnedSemaphorePermit, Semaphore},
task::JoinHandle,
};
#[derive(Clone, Debug)]
pub struct BoundedExecutor {
semaphore: Arc<Semaphore>,
executor: Handle,
}
impl BoundedExecutor {
pub fn new(capacity: usize, executor: Handle) -> Self {
let semaphore = Arc::new(Semaphore::new(capacity));
Self {
semaphore,
executor,
}
}
async fn acquire_permit(&self) -> OwnedSemaphorePermit {
self.semaphore.clone().acquire_owned().await.unwrap()
}
fn try_acquire_permit(&self) -> Option<OwnedSemaphorePermit> {
self.semaphore.clone().try_acquire_owned().ok()
}
pub async fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let permit = self.acquire_permit().await;
self.executor.spawn(future_with_permit(future, permit))
}
pub fn try_spawn<F>(&self, future: F) -> Result<JoinHandle<F::Output>, F>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
match self.try_acquire_permit() {
Some(permit) => Ok(self.executor.spawn(future_with_permit(future, permit))),
None => Err(future),
}
}
pub async fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let permit = self.acquire_permit().await;
self.executor
.spawn_blocking(function_with_permit(func, permit))
}
pub async fn try_spawn_blocking<F, R>(&self, func: F) -> Result<JoinHandle<R>, F>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
match self.try_acquire_permit() {
Some(permit) => Ok(self
.executor
.spawn_blocking(function_with_permit(func, permit))),
None => Err(func),
}
}
}
fn future_with_permit<F>(future: F, permit: OwnedSemaphorePermit) -> impl Future<Output = F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
future.map(move |ret| {
drop(permit);
ret
})
}
fn function_with_permit<F, R>(
func: F,
permit: OwnedSemaphorePermit,
) -> impl FnOnce() -> R + Send + 'static
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
move || {
let ret = func();
drop(permit);
ret
}
}
#[cfg(test)]
mod test {
use super::*;
use futures::{channel::oneshot, executor::block_on, future::Future};
use std::{
sync::atomic::{AtomicU32, Ordering},
time::Duration,
};
use tokio::{runtime::Runtime, time::sleep};
#[test]
fn try_spawn() {
let rt = Runtime::new().unwrap();
let executor = rt.handle().clone();
let executor = BoundedExecutor::new(1, executor);
let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();
let f1 = executor.try_spawn(rx1).unwrap();
let rx2 = executor.try_spawn(rx2).unwrap_err();
tx1.send(()).unwrap();
block_on(f1).unwrap().unwrap();
let f2 = executor.try_spawn(rx2).unwrap();
tx2.send(()).unwrap();
block_on(f2).unwrap().unwrap();
}
fn yield_task() -> impl Future<Output = ()> {
sleep(Duration::from_millis(1)).map(|_| ())
}
#[test]
fn concurrent_bounded_executor() {
const MAX_WORKERS: u32 = 20;
const NUM_TASKS: u32 = 1000;
static WORKERS: AtomicU32 = AtomicU32::new(0);
static COMPLETED_TASKS: AtomicU32 = AtomicU32::new(0);
let rt = Runtime::new().unwrap();
let executor = rt.handle().clone();
let executor = BoundedExecutor::new(MAX_WORKERS as usize, executor);
for _ in 0..NUM_TASKS {
block_on(executor.spawn(async move {
let prev_workers = WORKERS.fetch_add(1, Ordering::SeqCst);
assert!(prev_workers < MAX_WORKERS);
yield_task().await;
let prev_workers = WORKERS.fetch_sub(1, Ordering::SeqCst);
assert!(prev_workers > 0 && prev_workers <= MAX_WORKERS);
COMPLETED_TASKS.fetch_add(1, Ordering::Relaxed);
}));
}
loop {
let completed = COMPLETED_TASKS.load(Ordering::Relaxed);
if completed == NUM_TASKS {
break;
} else {
std::hint::spin_loop()
}
}
}
}