Skip to content

Instantly share code, notes, and snippets.

@aliakakis
Created November 12, 2025 15:32
Show Gist options
  • Select an option

  • Save aliakakis/d73b0ec9bf816b7117daa7a1fdfa80d7 to your computer and use it in GitHub Desktop.

Select an option

Save aliakakis/d73b0ec9bf816b7117daa7a1fdfa80d7 to your computer and use it in GitHub Desktop.
Rust dynamic queue
/*
Usage
async fn t0() {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
println!("Hello");
}
async fn t1() {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
println!("World");
}
#[tokio::main]
async fn main() {
env_logger::init(); // Log to stderr (if you run with `RUST_LOG=debug`).
let mut queue = Queue::new();
queue.en_queue(task!(t0()));
queue.en_queue(task!(t1()));
queue.run().await;
}
*/
use std::future::Future;
use std::pin::Pin;
type AsyncFn = Pin<Box<dyn Future<Output=()>>>;
macro_rules! task {
($function:expr) => {
Box::pin($function)
};
}
struct Queue {
tasks: Vec<AsyncFn>,
}
impl Queue {
fn new() -> Self {
Self { tasks: Vec::new() }
}
fn en_queue(&mut self, task: AsyncFn) {
self.tasks.insert(0, task);
}
async fn run(&mut self) {
while let Some(func) = self.tasks.pop() {
func.await;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment