1use std::{
2 collections::HashMap,
3 future::Future,
4 sync::{
5 Arc, Weak,
6 atomic::{AtomicUsize, Ordering},
7 },
8 thread::panicking,
9};
10
11use parking_lot::Mutex;
12
13use crate::async_runtime::{Executor, Task, global_executor};
14
15use super::{CondWait, Either, select};
16
17pub type TaskID = usize;
19
20pub struct TaskGroup {
41 inner: Arc<Inner>,
42}
43
44struct Inner {
48 tasks: Mutex<HashMap<TaskID, TaskHandler>>,
49 next_id: AtomicUsize,
50 executor: Executor,
51}
52
53impl Inner {
54 fn remove(&self, id: TaskID) -> Option<TaskHandler> {
56 self.tasks.lock().remove(&id)
57 }
58}
59
60impl TaskGroup {
61 pub fn new() -> Self {
66 Self::with_inner(global_executor())
67 }
68
69 pub fn with_executor(executor: Executor) -> Self {
71 Self::with_inner(executor)
72 }
73
74 fn with_inner(executor: Executor) -> Self {
75 Self {
76 inner: Arc::new(Inner {
77 tasks: Mutex::new(HashMap::new()),
78 next_id: AtomicUsize::new(0),
79 executor,
80 }),
81 }
82 }
83
84 pub fn spawn<T, Fut>(&self, fut: Fut) -> TaskID
89 where
90 T: Send + Sync + 'static,
91 Fut: Future<Output = T> + Send + 'static,
92 {
93 self.spawn_then(fut, |_| async {})
94 }
95
96 pub fn spawn_then<T, Fut, CallbackF, CallbackFut>(
102 &self,
103 fut: Fut,
104 callback: CallbackF,
105 ) -> TaskID
106 where
107 T: Send + Sync + 'static,
108 Fut: Future<Output = T> + Send + 'static,
109 CallbackF: FnOnce(TaskResult<T>) -> CallbackFut + Send + 'static,
110 CallbackFut: Future<Output = ()> + Send + 'static,
111 {
112 let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
113 let mut tasks = self.inner.tasks.lock();
116 let task = TaskHandler::new(
117 self.inner.executor.clone(),
118 fut,
119 callback,
120 Arc::downgrade(&self.inner),
121 id,
122 );
123 tasks.insert(id, task);
124 id
125 }
126
127 pub fn remove(&self, id: TaskID) -> Option<TaskHandler> {
130 self.inner.remove(id)
131 }
132
133 pub fn is_empty(&self) -> bool {
135 self.inner.tasks.lock().is_empty()
136 }
137
138 pub fn len(&self) -> usize {
140 self.inner.tasks.lock().len()
141 }
142
143 pub async fn cancel(&self) {
145 let handlers: Vec<TaskHandler> = self.inner.tasks.lock().drain().map(|(_, h)| h).collect();
147 for handler in handlers {
148 handler.cancel().await;
149 }
150 }
151}
152
153impl Default for TaskGroup {
154 fn default() -> Self {
155 Self::new()
156 }
157}
158
159#[derive(Debug)]
161pub enum TaskResult<T> {
162 Completed(T),
163 Cancelled,
164}
165
166impl<T: std::fmt::Debug> std::fmt::Display for TaskResult<T> {
167 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
168 match self {
169 TaskResult::Cancelled => write!(f, "Task cancelled"),
170 TaskResult::Completed(res) => write!(f, "Task completed: {res:?}"),
171 }
172 }
173}
174
175fn remove_from_group(group: &Weak<Inner>, id: TaskID) {
179 if let Some(group) = group.upgrade()
180 && let Some(handler) = group.remove(id)
181 {
182 handler.detach();
183 }
184}
185
186struct PanicGuard {
190 ex: Executor,
191 cancel_flag: Arc<CondWait>,
192 group: Weak<Inner>,
193 id: TaskID,
194}
195
196impl Drop for PanicGuard {
197 fn drop(&mut self) {
198 if !panicking() {
200 return;
201 }
202 let cancel_flag = self.cancel_flag.clone();
204 self.ex
205 .spawn(async move { cancel_flag.signal().await })
206 .detach();
207 remove_from_group(&self.group, self.id);
209 }
210}
211
212pub struct TaskHandler {
214 task: Task<()>,
215 stop_signal: Arc<CondWait>,
218 cancel_flag: Arc<CondWait>,
220}
221
222impl TaskHandler {
223 fn new<T, Fut, CallbackF, CallbackFut>(
225 ex: Executor,
226 fut: Fut,
227 callback: CallbackF,
228 group: Weak<Inner>,
229 id: TaskID,
230 ) -> TaskHandler
231 where
232 T: Send + Sync + 'static,
233 Fut: Future<Output = T> + Send + 'static,
234 CallbackF: FnOnce(TaskResult<T>) -> CallbackFut + Send + 'static,
235 CallbackFut: Future<Output = ()> + Send + 'static,
236 {
237 let stop_signal = Arc::new(CondWait::new());
238 let stop_signal_c = stop_signal.clone();
239 let cancel_flag = Arc::new(CondWait::new());
240 let cancel_flag_c = cancel_flag.clone();
241 let guard = PanicGuard {
242 ex: ex.clone(),
243 cancel_flag: cancel_flag.clone(),
244 group: group.clone(),
245 id,
246 };
247 let task = ex.spawn(async move {
248 let _guard = guard;
250
251 let result = select(stop_signal_c.wait(), fut).await;
253
254 let result = match result {
255 Either::Left(_) => TaskResult::Cancelled,
256 Either::Right(res) => TaskResult::Completed(res),
257 };
258
259 callback(result).await;
261
262 cancel_flag_c.signal().await;
263
264 remove_from_group(&group, id);
266 });
267
268 TaskHandler {
269 task,
270 stop_signal,
271 cancel_flag,
272 }
273 }
274
275 fn detach(self) {
277 self.task.detach();
278 }
279
280 async fn cancel(self) {
282 self.stop_signal.signal().await;
283 self.cancel_flag.wait().await;
284 self.detach();
287 }
288}
289
290#[cfg(test)]
291mod tests {
292 use std::{future, sync::Arc, time::Duration};
293
294 use crate::async_runtime::block_on;
295 use crate::async_util::{sleep, timeout};
296
297 use super::*;
298
299 #[cfg(feature = "tokio")]
300 #[test]
301 fn test_task_group_with_tokio_executor() {
302 let ex = Arc::new(tokio::runtime::Runtime::new().unwrap());
303 ex.clone().block_on(async move {
304 let group = Arc::new(TaskGroup::with_executor(ex.into()));
305
306 group.spawn_then(future::ready(0), |res| async move {
307 assert!(matches!(res, TaskResult::Completed(0)));
308 });
309
310 group.spawn_then(future::pending::<()>(), |res| async move {
311 assert!(matches!(res, TaskResult::Cancelled));
312 });
313
314 let groupc = group.clone();
315 group.spawn_then(
316 async move {
317 groupc.spawn_then(future::pending::<()>(), |res| async move {
318 assert!(matches!(res, TaskResult::Cancelled));
319 });
320 },
321 |res| async move {
322 assert!(matches!(res, TaskResult::Completed(_)));
323 },
324 );
325
326 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
328 group.cancel().await;
329 });
330 }
331
332 #[cfg(feature = "smol")]
333 #[test]
334 fn test_task_group_with_smol_executor() {
335 let ex = Arc::new(smol::Executor::new());
336 smol::block_on(ex.clone().run(async move {
337 let group = Arc::new(TaskGroup::with_executor(ex.into()));
338
339 group.spawn_then(future::ready(0), |res| async move {
340 assert!(matches!(res, TaskResult::Completed(0)));
341 });
342
343 group.spawn_then(future::pending::<()>(), |res| async move {
344 assert!(matches!(res, TaskResult::Cancelled));
345 });
346
347 let groupc = group.clone();
348 group.spawn_then(
349 async move {
350 groupc.spawn_then(future::pending::<()>(), |res| async move {
351 assert!(matches!(res, TaskResult::Cancelled));
352 });
353 },
354 |res| async move {
355 assert!(matches!(res, TaskResult::Completed(_)));
356 },
357 );
358
359 smol::Timer::after(std::time::Duration::from_millis(50)).await;
361 group.cancel().await;
362 }));
363 }
364
365 #[test]
366 fn test_task_group() {
367 block_on(async {
368 let group = Arc::new(TaskGroup::new());
369
370 group.spawn_then(future::ready(0), |res| async move {
371 assert!(matches!(res, TaskResult::Completed(0)));
372 });
373
374 group.spawn_then(future::pending::<()>(), |res| async move {
375 assert!(matches!(res, TaskResult::Cancelled));
376 });
377
378 let groupc = group.clone();
379 group.spawn_then(
380 async move {
381 groupc.spawn_then(future::pending::<()>(), |res| async move {
382 assert!(matches!(res, TaskResult::Cancelled));
383 });
384 },
385 |res| async move {
386 assert!(matches!(res, TaskResult::Completed(_)));
387 },
388 );
389
390 sleep(std::time::Duration::from_millis(50)).await;
392 group.cancel().await;
393 });
394 }
395
396 #[test]
397 fn test_task_group_removes_finished_tasks() {
398 block_on(async {
399 let group = Arc::new(TaskGroup::new());
400
401 group.spawn(future::ready(0));
403 group.spawn(future::pending::<()>());
404
405 sleep(std::time::Duration::from_millis(50)).await;
406 assert_eq!(group.len(), 1);
407
408 group.cancel().await;
409 assert!(group.is_empty());
410 });
411 }
412
413 #[test]
414 fn test_task_group_remove_by_id() {
415 block_on(async {
416 let group = Arc::new(TaskGroup::new());
417
418 let id = group.spawn(future::pending::<()>());
419 assert_eq!(group.len(), 1);
420
421 let handler = group.remove(id).expect("task is present");
422 assert!(group.is_empty());
423 handler.cancel().await;
424 });
425 }
426
427 #[test]
428 fn test_task_group_cancel_after_panic() {
429 block_on(async {
430 let group = TaskGroup::new();
431 group.spawn(async { panic!("task panic") });
432
433 let res = timeout(Duration::from_secs(5), group.cancel()).await;
435 assert!(res.is_ok());
436 });
437 }
438
439 #[test]
440 fn test_task_group_removes_panicked_tasks() {
441 block_on(async {
442 let group = TaskGroup::new();
443 group.spawn_then(future::ready(0), |_| async { panic!("callback panic") });
444 group.spawn(async { panic!("task panic") });
445
446 sleep(Duration::from_millis(50)).await;
447 assert!(group.is_empty());
448 });
449 }
450}