use async_std::task;
use std::collections::VecDeque;
struct TaskQueue {
tasks: VecDeque<Box<dyn FnMut() -> impl std::future::Future<Output = ()>>>,
}
impl TaskQueue {
fn new() -> Self {
TaskQueue {
tasks: VecDeque::new(),
}
}
fn push_task(&mut self, task: impl FnMut() -> impl std::future::Future<Output = ()> + 'static) {
self.tasks.push_back(Box::new(task));
}
async fn execute(&mut self) {
while let Some(mut task) = self.tasks.pop_front() {
task().await;
}
}
}
#[async_std::main]
async fn main() {
let mut queue = TaskQueue::new();
let mut data = 0;
queue.push_task(move || {
async move {
task::sleep(std::time::Duration::from_secs(1)).await;
data += 1;
println!("Task 1 executed, data: {}", data);
}
});
queue.push_task(move || {
async move {
task::sleep(std::time::Duration::from_secs(1)).await;
data *= 2;
println!("Task 2 executed, data: {}", data);
}
});
queue.execute().await;
}