Skip to content

Instantly share code, notes, and snippets.

@0ex-d
Created December 31, 2024 20:31
Show Gist options
  • Save 0ex-d/17b0d18f85befff34fdc51cd8389ecdf to your computer and use it in GitHub Desktop.
Save 0ex-d/17b0d18f85befff34fdc51cd8389ecdf to your computer and use it in GitHub Desktop.
Cheapest tokio-sponsored blue collar worker you could hire
use tokio::time::{sleep, Duration, Instant};
use anyhow::Result;
use thiserror::Error;
#[derive(Error,Debug)]
enum WorkerError {
#[error("Worker {0} encountered an error")]
Failed(isize),
}
async fn worker(idx: isize) -> Result<(), WorkerError> {
println!("starting worker {idx}");
// <do some I/O op here>
sleep(Duration::from_secs(2)).await;
// sim an error for demonstration
if idx == 3 {
return Err(WorkerError::Failed(idx));
}
println!("worker {idx} done");
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
let start_ts = Instant::now();
let range_of_souls = 1..10;
let handles: Vec<_> = range_of_souls
.map(|id| tokio::spawn(worker(id)))
.collect();
for handle in handles {
// 1st `?` handles the JoinHandle Type
// 2nd `?` unwrap the result
handle.await??;
}
println!("all workers done. took {:?}", start_ts.elapsed());
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment