Last active
August 17, 2024 19:02
-
-
Save fancellu/e0fe0696e6f32df8ff077a7a7029c814 to your computer and use it in GitHub Desktop.
Rust example of tokio::spawn and JoinHandle processing
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
async fn hello(name: &str) -> String { | |
// pretend to be doing some work | |
tokio::time::sleep(std::time::Duration::from_secs(1)).await; | |
format!("Hello {}", name) | |
} | |
fn blocking() -> String { | |
println!("Blocking"); | |
// pretend to be doing some work | |
// sleep for 3 second, blocking | |
std::thread::sleep(std::time::Duration::from_secs(3)); | |
// return a string | |
"Blocked returning".to_string() | |
} | |
async fn bang() -> String { | |
tokio::time::sleep(std::time::Duration::from_secs(1)).await; | |
panic!("I just went bang") | |
} | |
// Example of an async unit test, cargo test to run | |
#[tokio::test] | |
async fn test_hello() { | |
let val = hello("Dino").await; | |
assert_eq!(val, "Hello Dino"); | |
} | |
#[tokio::main] | |
async fn main() { | |
// To stop us from getting an annoying backtrace on panic! | |
// We still handle the exception/JoinError later on. | |
std::panic::set_hook(Box::new(|_info| { | |
// do nothing | |
})); | |
// A bit like a Fibre | |
let join_handle = tokio::spawn(hello("Dino")); | |
let join_handle2 = tokio::spawn(hello("Charles")); | |
let join_handle3 = tokio::spawn(bang()); | |
// We get joinHandle on blocking tasks too, so we can treat them the same | |
let join_handle4 = tokio::task::spawn_blocking(blocking); | |
println!("Waiting for JoinHandles to return"); | |
let val = join_handle.await.unwrap(); | |
let val2 = join_handle2.await.unwrap(); | |
println!("Waiting for bang to return"); | |
let val3 = join_handle3.await; | |
let val3 = val3.unwrap_or_else(|e| { | |
println!("Exception: {}", e); | |
"I'm fine".to_string() | |
}); | |
println!("val={} val2={} val3={}", val, val2, val3); | |
let val4 = join_handle4.await.unwrap(); | |
println!("val4={}", val4); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
Waiting for JoinHandles to return
Blocking
Waiting for bang to return
Exception: task 35 panicked
val=Hello Dino val2=Hello Charles val3=I'm fine
val4=Blocked returning