6
With Rust 1.9,我想從mpsc::channel
或超時讀取。有這樣一個明確的習慣做法嗎?我已經看到mpsc::Select
中描述的不穩定方法,但this Github discussion表明它不是一種穩健的方法。有沒有一種更好的推薦方式來實現接收或超時語義?從通道讀取或超時?
With Rust 1.9,我想從mpsc::channel
或超時讀取。有這樣一個明確的習慣做法嗎?我已經看到mpsc::Select
中描述的不穩定方法,但this Github discussion表明它不是一種穩健的方法。有沒有一種更好的推薦方式來實現接收或超時語義?從通道讀取或超時?
我不知道你會如何與標準庫的渠道去做,但chan crate提供chan_select!
宏:
#[macro_use]
extern crate chan;
use std::time::Duration;
fn main() {
let (_never_sends, never_receives) = chan::sync::<bool>(1);
let timeout = chan::after(Duration::from_millis(50));
chan_select! {
timeout.recv() => {
println!("timed out!");
},
never_receives.recv() => {
println!("Shouldn't have a value!");
},
}
}
鏽1.12介紹Receiver::recv_timeout
:
use std::sync::mpsc::channel;
use std::time::Duration;
fn main() {
let (.., rx) = channel::<bool>();
let timeout = Duration::new(3, 0);
println!("start recv");
let _ = rx.recv_timeout(timeout);
println!("done!");
}