用 oneshot 功能创造未来
期货箱中有一些普遍的 Future
特质实施。其中一个是在 futures::sync::oneshot
模块中实现的,可以通过 futures::oneshot
函数获得:
extern crate futures;
use std::thread;
use futures::Future;
fn expensive_computation() -> u32 {
// ...
200
}
fn main() {
// The oneshot function returns a tuple of a Sender and a Receiver.
let (tx, rx) = futures::oneshot();
thread::spawn(move || {
// The complete method resolves a values.
tx.complete(expensive_computation());
});
// The map method applies a function to a value, when it is resolved.
let rx = rx.map(|x| {
println!("{}", x);
});
// The wait method blocks current thread until the value is resolved.
rx.wait().unwrap();
}