Last active
October 17, 2022 06:48
-
-
Save SoTosorrow/45406ec3b793b58845f4c890e32a45eb to your computer and use it in GitHub Desktop.
coroutine and async in tokio
This file contains 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
tokio::runtime::Builder::new_multi_thread().worker_threads(4).enable_all().build().unwrap().block_on( | |
async{ | |
let mut handles = Vec::with_capacity(8); | |
for i in 1..4{ | |
let joinhandle = tokio::spawn(async move{ | |
tokio::task::yield_now().await; | |
co_run(i).await; | |
}); | |
handles.push(joinhandle); | |
// joinhandle.await; // sequence | |
} | |
futures::future::join_all(handles).await; | |
} | |
); | |
} | |
async fn co_run(id : i32){ | |
println!("begin {}",id); | |
// simulate io time wait | |
let result = co_sleep(1).await; | |
println!("end {}:{}",id,result); | |
} | |
async fn co_sleep(num : i32) -> i32{ | |
std::thread::sleep(std::time::Duration::from_secs(1)); | |
num+1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment