【问题标题】:Why is an async fn() called from Future::poll() not executed at the time of execution?为什么在执行时未执行从 Future::poll() 调用的 async fn()?
【发布时间】:2021-01-11 23:18:48
【问题描述】:

我在Future::poll() 中调用了async fn(),但.await 语句及其背后的代码在执行时并未执行。

use futures::FutureExt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

#[pin_project::pin_project]
struct Person<'a> {
    name: &'a str,
    age: i32,
}

impl<'a> Future for Person<'a> {
    type Output = i32;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();
        *this.age += 10;

        let mut fut1 = fn1();
        let pinfut1 = Pin::new(&mut fut1);
        //let pinfut1 = unsafe { Pin::new_unchecked(&mut fut1) };
        pinfut1.poll(cx)
    }
}

fn fn1() -> impl Future<Output = i32> + Unpin {
    async {
        dbg!("sleep start!"); // execute here!
        async_std::task::sleep(std::time::Duration::from_secs(5)).await; //  <--- blocked here ?
        dbg!("sleep done!"); // Never execute here!
        123
    }
    .boxed()
}

fn main() {
    let p1 = Person {
        name: "jack",
        age: Default::default(),
    };
    async_std::task::block_on(async {
        let a = p1.await;
        dbg!(a); // Never execute here!
    });
    std::thread::park();
}

playground

Cargo.toml:

[package]
name = "test-poll"
version = "0.1.0"
authors = ["xx <xx@xx.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
async-std="1.8.0"
pin-project="0.4.6"
futures=""

【问题讨论】:

  • 这个帖子有操场比较清楚一点,只是那个帖子因为我的原因,跑题了。

标签: rust async-await future


【解决方案1】:

每次轮询您的 Person 未来时,您都会创建一个全新的 fn1 未来:

let mut fut1 = fn1();

future 等待 5 秒,然后唤醒执行程序,轮询 Person,然后创建一个全新的 fn1future,等待 5 秒...

请参阅How to implement a Future or Stream that polls an async fn? 以获取有关如何正确执行此操作的说明(尽管我同意您可能一开始就想这样做)。

【讨论】:

    猜你喜欢
    • 2020-02-25
    • 2021-07-12
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多