Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,47 @@ impl<'a> Executor<'a> {
// and will never be moved until it's dropped.
Pin::new(unsafe { &*ptr })
}

pub fn scope<'e, R>(
&'e self,
callback: impl FnOnce(&mut Scope<'e>) -> R,
) -> impl Future<Output = R> {
let mut scope = Scope::new(self.state().get_ref());
let res = callback(&mut scope);
let joined = async move {
let tasks = scope.tasks;
for task in tasks {
task.await;
}
res
};
joined
}
}

pub struct Scope<'e> {
state: Pin<&'e State>,
tasks: Vec<Task<()>>,
}

impl<'e> Scope<'e> {
fn new(state: &'e State) -> Self {
Scope {
state: Pin::new(state),
tasks: Vec::new(),
}
}

pub fn spawn<F, R>(&mut self, future: F)
where
F: Future<Output = R> + Send + 'e,
{
let future = async {
_ = future.await;
};
let task = unsafe { Executor::spawn_inner(self.state, future, &mut self.state.active()) };
self.tasks.push(task);
}
}

impl Drop for Executor<'_> {
Expand Down
19 changes: 19 additions & 0 deletions tests/scope.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use async_executor::Executor;

#[test]
fn test_basic_scope() {
let ex = Executor::new();
let data = std::sync::Mutex::new(0i32);
futures_lite::future::block_on(ex.run(async {
ex.scope(|scope| {
scope.spawn(async {
*data.lock().unwrap() += 1;
});
scope.spawn(async {
*data.lock().unwrap() += 4;
});
})
.await;
}));
assert_eq!(*data.lock().unwrap(), 5);
}
Loading