美文网首页
理解 rust 中的 futures(九)

理解 rust 中的 futures(九)

作者: 西门早柿 | 来源:发表于2021-03-01 22:15 被阅读0次
工具函数

首先,我们需要一些工具函数,future::readyblock_on。这些工具函数虽然在生产代码中并不常见,但却能使我们方便的创建和运行 futures。

在开始之前,让我们把 Future trait 和 Context 结构体放进 modules 中,使其与标准库中的代码结构相同。

mod task {
    use crate::NOTIFY;

    pub struct Context<'a> {
        waker: &'a Waker,
    }

    impl<'a> Context<'a> {
        pub fn from_waker(waker: &'a Waker) -> Self {
            Context { waker }
        }

        pub fn waker(&self) -> &'a Waker {
            &self.waker
        }
    }

    pub struct Waker;

    impl Waker {
        pub fn wake(&self) {
            NOTIFY.with(|f| *f.borrow_mut() = true)
        }
    }

}
use crate::task::*;

mod future {
    use crate::task::*;

    pub enum Poll<T> {
        Ready(T),
        Pending,
    }

    pub trait Future {
        type Output;

        fn poll(&mut self, cx: &Context) -> Poll<Self::Output>;
    }
}
use crate::future::*;

Playground Link

这里主要需要注意的是 modules、types 和 function 都要声明成 public 的,以便舍使得我们可以在剩余的代码中可以直接调用。pub 关键字可以帮我们完成这点。

相关文章

网友评论

      本文标题:理解 rust 中的 futures(九)

      本文链接:https://www.haomeiwen.com/subject/fiffqltx.html