Skip to content

Instantly share code, notes, and snippets.

@SoTosorrow
Last active October 17, 2022 06:48
Show Gist options
  • Save SoTosorrow/45406ec3b793b58845f4c890e32a45eb to your computer and use it in GitHub Desktop.
Save SoTosorrow/45406ec3b793b58845f4c890e32a45eb to your computer and use it in GitHub Desktop.
coroutine and async in tokio
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