【发布时间】:2018-07-22 00:02:43
【问题描述】:
我试图理解Future::select:在这个例子中,首先返回具有较长时间延迟的未来。
当我读到 this article 的例子时,我感到认知失调。作者写道:
select函数运行两个(如果是select_all则更多)期货并返回第一个即将完成的期货。这对于实现超时很有用。
我好像不懂select的意思。
extern crate futures; // v0.1 (old)
extern crate tokio_core;
use std::thread;
use std::time::Duration;
use futures::{Async, Future};
use tokio_core::reactor::Core;
struct Timeout {
time: u32,
}
impl Timeout {
fn new(period: u32) -> Timeout {
Timeout { time: period }
}
}
impl Future for Timeout {
type Item = u32;
type Error = String;
fn poll(&mut self) -> Result<Async<u32>, Self::Error> {
thread::sleep(Duration::from_secs(self.time as u64));
println!("Timeout is done with time {}.", self.time);
Ok(Async::Ready(self.time))
}
}
fn main() {
let mut reactor = Core::new().unwrap();
let time_out1 = Timeout::new(5);
let time_out2 = Timeout::new(1);
let task = time_out1.select(time_out2);
let mut reactor = Core::new().unwrap();
reactor.run(task);
}
我需要处理时间延迟较小的早期未来,然后处理延迟较长的未来。我该怎么做?
【问题讨论】: