期货::期货::懒惰的目的是什么?

lit*_*ude 1 future rust rust-tokio

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(())
}));
Run Code Online (Sandbox Code Playgroud)

对此的解释是:

lazy函数在第一次对将来进行轮询时运行关闭。在这里使用它来确保tokio::spawn从任务中调用。如果不使用lazytokio::spawn则会从任务的上下文外部调用它,从而导致错误。

尽管对Tokio有所了解,但我不确定我是否能准确理解。看来这两个lazy角色的作用略有不同,并且这种解释仅适用于一个。难道不是在这里lazy(在for循环内)第二次调用将闭包转换为未来吗?

She*_*ter 6

文档中涵盖了惰性的目的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();
}
Run Code Online (Sandbox Code Playgroud)

和期货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();
}
Run Code Online (Sandbox Code Playgroud)

使用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);
}
Run Code Online (Sandbox Code Playgroud)

如您所知,Tokio的示例用于lazy

  • 确保闭包中的代码仅从执行程序内部运行。
  • 确保关闭将在将来运行

我认为这两个方面lazy实际上是相同的。

也可以看看: