From 379dca552ca91d22ee007b42f93803ad3dc2b274 Mon Sep 17 00:00:00 2001 From: hozan23 Date: Wed, 20 Mar 2024 15:20:21 +0100 Subject: core: add the option to create a new task group without providing an executor & remove GlobalExecutor type --- core/src/async_util/task_group.rs | 48 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 3 deletions(-) (limited to 'core/src/async_util/task_group.rs') 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; + }); + } } -- cgit v1.2.3