Skip to content

Instantly share code, notes, and snippets.

@snoyberg

snoyberg/main.rs Secret

Created November 19, 2025 09:47
Show Gist options
  • Select an option

  • Save snoyberg/343c46a6caac19d820d3ef27ba2f3c63 to your computer and use it in GitHub Desktop.

Select an option

Save snoyberg/343c46a6caac19d820d3ef27ba2f3c63 to your computer and use it in GitHub Desktop.
use std::convert::Infallible;
mod join_set;
fn background_task1<T>() -> T {
loop {
println!("Performing background task 1.");
std::thread::sleep(std::time::Duration::from_secs(60));
}
}
fn background_task2() -> Result<Infallible, String> {
let mut counter = 0;
loop {
counter += 1;
println!("Performing background task 2.");
std::thread::sleep(std::time::Duration::from_secs(2));
if counter >= 3 {
return Err("Background task 2 errored".to_owned());
}
}
}
fn main() -> Result<(), String> {
let mut set = join_set::JoinSet::new();
set.spawn(background_task1);
set.spawn(background_task2);
let res = set
.join_next()
.expect("Impossible: received a None from join_next, but there are threads");
match res {
Err(e) => Err(format!("Background task panicked: {e:?}")),
Ok(Err(e)) => Err(format!("Background task errored out: {e}")),
// Automaticaly understood by the compiler
// Ok(Ok(())) => panic!("Unexpected background job exit"),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment