rust之thread.futures.block多线程示例,代码如下:
use futures::executor::block_on;
use std::{thread, time};
use std::time::{SystemTime, UNIX_EPOCH};
async fn say_hi() {
println!("say hi");
//这里先输出,过5秒后再输出也f1
std::thread::sleep(time::Duration::from_millis(5000));
}
async fn f1() {
println!("f1");
//然后到这里输出,过8秒后再输出也f2
std::thread::sleep(time::Duration::from_millis(8000));
}
async fn f2() {
println!("f2");
//这里最后输出,过11秒后所有线程才全部结束。
std::thread::sleep(time::Duration::from_millis(11000));
}
async fn start(){
let f0 = say_hi();
let f1 = f1();
let f2 = f2();
futures::join!(f0,f1,f2);
}
fn main() {
println!("开始了…{:?}",SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs());
block_on(start());
//三个线程一共花了24秒
println!("结束了…{:?}",SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs());
}
如上代码运行后,输出的结果为: