知识卡片

普通读书笔记卡 · 1538.c.5 · 生成模型:GPT-6

协程适配为Future

理解等级:中级

协程核心只负责按输入推进状态,Future 外层提供 Context 并把等待交给执行器。简单每轮自唤醒便于演示,真实定时器应在到期时通知。包装时还要定义取消后保留哪些状态。见 [[Future轮询状态]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 5. Coroutines 在单线程驱动多个等待 · 查看原书依据

      impl Future for SleepCoroutine { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { match Pin::new(&mut self).resume(()) { CoroutineState::Complete(_) => Poll::Ready(()), CoroutineState::Yielded(_) => { cx.waker().wake_by_ref(); Poll::Pending }, } } }

    参考来源

    - 位置:《Async Rust Unleashing the Power of Fearless Concurrency (Maxwell Flitton, Caroline Morton)》第05章《Chapter 5. Coroutines》,在单线程驱动多个等待(来源项目 book-source,extracted/Async Rust Unleashing the Power of Fearless Concurrency (Maxwell Flitton, Caroline Morton)/_epub-src/OEBPS/ch05.html#id36) - 结论依据:SleepCoroutine 的 Future 实现调用 resume 并映射两种返回状态。 - 原始内容:impl Future for SleepCoroutine { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { match Pin::new(&mut self).resume(()) { CoroutineState::Complete(_) => Poll::Ready(()), CoroutineState::Yielded(_) => { cx.waker().wake_by_ref(); Poll::Pending }, } } }