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
|
use std::{future::Future, sync::Arc};
use parking_lot::Mutex;
use crate::async_runtime::{global_executor, Executor, Task};
use super::{select, CondWait, Either};
/// TaskGroup A group that contains spawned tasks.
///
/// # Example
///
/// ```
///
/// use std::sync::Arc;
///
/// use karyon_core::async_util::{TaskGroup, sleep};
///
/// async {
/// let group = TaskGroup::new();
///
/// group.spawn(sleep(std::time::Duration::MAX), |_| async {});
///
/// group.cancel().await;
///
/// };
///
/// ```
pub struct TaskGroup {
tasks: Mutex<Vec<TaskHandler>>,
stop_signal: Arc<CondWait>,
executor: Executor,
}
impl TaskGroup {
/// Creates a new TaskGroup without providing an executor
///
/// This will spawn a task onto a global executor (single-threaded by default).
pub fn new() -> Self {
Self {
tasks: Mutex::new(Vec::new()),
stop_signal: Arc::new(CondWait::new()),
executor: global_executor(),
}
}
/// Creates a new TaskGroup by providing an executor
pub fn with_executor(executor: Executor) -> Self {
Self {
tasks: Mutex::new(Vec::new()),
stop_signal: Arc::new(CondWait::new()),
executor,
}
}
/// Spawns a new task and calls the callback after it has completed
/// or been canceled. The callback will have the `TaskResult` as a
/// parameter, indicating whether the task completed or was canceled.
pub fn spawn<T, Fut, CallbackF, CallbackFut>(&self, fut: Fut, callback: CallbackF)
where
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
CallbackF: FnOnce(TaskResult<T>) -> CallbackFut + Send + 'static,
CallbackFut: Future<Output = ()> + Send + 'static,
{
let task = TaskHandler::new(
self.executor.clone(),
fut,
callback,
self.stop_signal.clone(),
);
self.tasks.lock().push(task);
}
/// Checks if the TaskGroup is empty.
pub fn is_empty(&self) -> bool {
self.tasks.lock().is_empty()
}
/// Get the number of the tasks in the group.
pub fn len(&self) -> usize {
self.tasks.lock().len()
}
/// Cancels all tasks in the group.
pub async fn cancel(&self) {
self.stop_signal.broadcast().await;
loop {
// XXX BE CAREFUL HERE, it hold synchronous mutex across .await point.
let task = self.tasks.lock().pop();
if let Some(t) = task {
t.cancel().await
} else {
break;
}
}
}
}
impl Default for TaskGroup {
fn default() -> Self {
Self::new()
}
}
/// The result of a spawned task.
#[derive(Debug)]
pub enum TaskResult<T> {
Completed(T),
Cancelled,
}
impl<T: std::fmt::Debug> std::fmt::Display for TaskResult<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
TaskResult::Cancelled => write!(f, "Task cancelled"),
TaskResult::Completed(res) => write!(f, "Task completed: {:?}", res),
}
}
}
/// TaskHandler
pub struct TaskHandler {
task: Task<()>,
cancel_flag: Arc<CondWait>,
}
impl<'a> TaskHandler {
/// Creates a new task handler
fn new<T, Fut, CallbackF, CallbackFut>(
ex: Executor,
fut: Fut,
callback: CallbackF,
stop_signal: Arc<CondWait>,
) -> TaskHandler
where
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
CallbackF: FnOnce(TaskResult<T>) -> CallbackFut + Send + 'static,
CallbackFut: Future<Output = ()> + Send + 'static,
{
let cancel_flag = Arc::new(CondWait::new());
let cancel_flag_c = cancel_flag.clone();
let task = ex.spawn(async move {
// Waits for either the stop signal or the task to complete.
let result = select(stop_signal.wait(), fut).await;
let result = match result {
Either::Left(_) => TaskResult::Cancelled,
Either::Right(res) => TaskResult::Completed(res),
};
// Call the callback
callback(result).await;
cancel_flag_c.signal().await;
});
TaskHandler { task, cancel_flag }
}
/// Cancels the task.
async fn cancel(self) {
self.cancel_flag.wait().await;
self.task.cancel().await;
}
}
#[cfg(test)]
mod tests {
use std::{future, sync::Arc};
use crate::async_runtime::block_on;
use crate::async_util::sleep;
use super::*;
#[cfg(feature = "tokio")]
#[test]
fn test_task_group_with_tokio_executor() {
let ex = Arc::new(tokio::runtime::Runtime::new().unwrap());
ex.clone().block_on(async move {
let group = Arc::new(TaskGroup::with_executor(ex.into()));
group.spawn(future::ready(0), |res| async move {
assert!(matches!(res, TaskResult::Completed(0)));
});
group.spawn(future::pending::<()>(), |res| async move {
assert!(matches!(res, TaskResult::Cancelled));
});
let groupc = group.clone();
group.spawn(
async move {
groupc.spawn(future::pending::<()>(), |res| async move {
assert!(matches!(res, TaskResult::Cancelled));
});
},
|res| async move {
assert!(matches!(res, TaskResult::Completed(_)));
},
);
// Do something
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
group.cancel().await;
});
}
#[cfg(feature = "smol")]
#[test]
fn test_task_group_with_smol_executor() {
let ex = Arc::new(smol::Executor::new());
smol::block_on(ex.clone().run(async move {
let group = Arc::new(TaskGroup::with_executor(ex.into()));
group.spawn(future::ready(0), |res| async move {
assert!(matches!(res, TaskResult::Completed(0)));
});
group.spawn(future::pending::<()>(), |res| async move {
assert!(matches!(res, TaskResult::Cancelled));
});
let groupc = group.clone();
group.spawn(
async move {
groupc.spawn(future::pending::<()>(), |res| async move {
assert!(matches!(res, TaskResult::Cancelled));
});
},
|res| async move {
assert!(matches!(res, TaskResult::Completed(_)));
},
);
// Do something
smol::Timer::after(std::time::Duration::from_millis(50)).await;
group.cancel().await;
}));
}
#[test]
fn test_task_group() {
block_on(async {
let group = Arc::new(TaskGroup::new());
group.spawn(future::ready(0), |res| async move {
assert!(matches!(res, TaskResult::Completed(0)));
});
group.spawn(future::pending::<()>(), |res| async move {
assert!(matches!(res, TaskResult::Cancelled));
});
let groupc = group.clone();
group.spawn(
async move {
groupc.spawn(future::pending::<()>(), |res| async move {
assert!(matches!(res, TaskResult::Cancelled));
});
},
|res| async move {
assert!(matches!(res, TaskResult::Completed(_)));
},
);
// Do something
sleep(std::time::Duration::from_millis(50)).await;
group.cancel().await;
});
}
}
|