下面的程序应该从多个线程定期打印,但tokio::time::sleep
没有按我预期的那样工作:
use tokio::prelude::*; //0.3.4
use tokio::runtime::Builder;
use tokio::time::Duration;
fn main() {
let rt = Builder::new_multi_thread()
.enable_all()
.thread_stack_size(3 * 1024 * 1024)
.build()
.unwrap();
rt.block_on(async {
tokio::spawn(print_thread(1));
tokio::spawn(print_thread(2));
tokio::spawn(print_thread(3));
tokio::spawn(print_thread(4));
});
}
async fn print_thread(thread_num: usize) {
tokio::spawn(async move {
println!("thread{}-start", thread_num);
loop {
tokio::time::sleep(Duration::from_millis(1000)).await;
println!("thread{}-running", thread_num);
}
println!("thread{}-start", thread_num);
});
}
它的输出是
$cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.64s
Running `target/debug/time_test`
thread1-start
thread2-start
thread3-start
thread4-start
$
我希望看到消息threadN-running
,但没有输出。我不知道为什么程序突然退出。有人可以告诉我原因吗?
我的Cargo.toml
样子是这样的:
[package]
name = "time_test"
version = "0.1.0"
edition = "2018"
[dependencies]
tokio = { version = "0.3", features = ["full"] }
另外,我的货物版本是:
$ cargo --version
cargo 1.48.0 (65cbdd2dc 2020-10-14)