diff options
Diffstat (limited to 'core/src/async_util/task_group.rs')
-rw-r--r-- | core/src/async_util/task_group.rs | 48 |
1 files changed, 45 insertions, 3 deletions
diff --git a/core/src/async_util/task_group.rs b/core/src/async_util/task_group.rs index 7129af2..0fb4855 100644 --- a/core/src/async_util/task_group.rs +++ b/core/src/async_util/task_group.rs @@ -2,9 +2,7 @@ use std::{future::Future, sync::Arc, sync::Mutex}; use async_task::FallibleTask; -use crate::Executor; - -use super::{select, CondWait, Either}; +use super::{executor::global_executor, select, CondWait, Either, Executor}; /// TaskGroup is a group of spawned tasks. /// @@ -35,6 +33,19 @@ pub struct TaskGroup<'a> { executor: Executor<'a>, } +impl TaskGroup<'static> { + /// Creates a new task group without providing an executor + /// + /// This will Spawn a task onto a global executor (single-threaded by default). + pub fn new_without_executor() -> Self { + Self { + tasks: Mutex::new(Vec::new()), + stop_signal: Arc::new(CondWait::new()), + executor: global_executor(), + } + } +} + impl<'a> TaskGroup<'a> { /// Creates a new task group pub fn new(executor: Executor<'a>) -> Self { @@ -191,4 +202,35 @@ mod tests { group.cancel().await; })); } + + #[test] + fn test_task_group_without_executor() { + smol::block_on(async { + let group = Arc::new(TaskGroup::new_without_executor()); + + 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; + }); + } } |