启动两个异步任务,一个阻塞在键盘输入。一个间歇的读取通道,有数据就输出。在快速输入的时候会卡住,因为 mpsc 的 buffer 设置为了 5。 代码如下:
use std::io;
use tokio::task;
use tokio::sync::mpsc;
use std::io::{Read, BufRead};
#[tokio::main]
async fn main() {
// input
let (mut tx_in, mut rx_in) = mpsc::channel::(5);
task::spawn(async move {
loop {
let line = task::spawn_blocking(move || {
let stdin = io::stdin();
let line = stdin.lock()
.lines()
.next()
.expect("there was no next line")
.expect("the line could not be read");
line
}).await.unwrap();
println!("send: {}", line);
tx_in.send(line).await.unwrap();
}
});
// work
task::spawn(async move {
loop {
tokio::time::delay_for(tokio::time::Duration::from_millis(1000)).await;
match rx_in.recv().await {
Some(data) => {
println!("data: {}", data);
},
None => ()
}
}
});
std::thread::park();
println!("Hello, world!");
}