-
-
Save snoyberg/343c46a6caac19d820d3ef27ba2f3c63 to your computer and use it in GitHub Desktop.
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 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