在Tokio文档中,我们有这样的片段:
extern crate tokio;
extern crate futures;
use futures::future::lazy;
tokio::run(lazy(|| {
for i in 0..4 {
tokio::spawn(lazy(move || {
println!("Hello from task {}", i);
Ok(())
}));
}
Ok(())
}));对此的解释是:
lazy函数在第一次轮询未来时运行闭包。这里使用它来确保从任务中调用tokio::spawn。如果没有lazy,将从任务上下文之外调用tokio::spawn,这将导致错误。
我不确定我是否确切地理解了这一点,尽管我对Tokio有些熟悉。这两个lazy的角色似乎略有不同,这种解释只适用于第一个角色。第二次调用lazy (在for循环中)不是只是为了将闭包转换为将来吗?
发布于 2019-06-11 13:16:10
lazy涵盖了懒惰的目的。
创造一个新的未来,它最终将与所提供的关闭所创造的未来相同。 提供的闭包只运行一次未来的回调计划,否则回调永远不会运行。但是,一旦运行,这个未来将与闭包创建的未来相同。
就像一个简单的闭包,它被用来防止代码被急切地计算。在同步术语中,调用函数与调用函数返回的闭包之间的区别是:
fn sync() -> impl FnOnce() {
println!("This is run when the function is called");
|| println!("This is run when the return value is called")
}
fn main() {
let a = sync();
println!("Called the function");
a();
}期货的平行值为0.1:
use futures::{future, Future}; // 0.1.27
fn not_sync() -> impl Future<Item = (), Error = ()> {
println!("This is run when the function is called");
future::lazy(|| {
println!("This is run when the return value is called");
Ok(())
})
}
fn main() {
let a = not_sync();
println!("Called the function");
a.wait().unwrap();
}使用async/await语法,应该不再需要这个函数了:
#![feature(async_await)] // 1.37.0-nightly (2019-06-05)
use futures::executor; // 0.3.0-alpha.16
use std::future::Future;
fn not_sync() -> impl Future<Output = ()> {
println!("This is run when the function is called");
async {
println!("This is run when the return value is called");
}
}
fn main() {
let a = not_sync();
println!("Called the function");
executor::block_on(a);
}正如您已经指出的,Tokio的示例使用lazy来:
我认为lazy的这两个方面实际上是相同的。
另请参阅:
https://stackoverflow.com/questions/56544469
复制相似问题