Created
December 31, 2024 20:31
-
-
Save 0ex-d/17b0d18f85befff34fdc51cd8389ecdf to your computer and use it in GitHub Desktop.
Cheapest tokio-sponsored blue collar worker you could hire
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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