asynchronous - tokio async rust 上的 Yield 是什么意思?

标签 asynchronous rust rust-tokio

在阅读 Tokio rust 文档时,它谈到将控制权交还给线程。这是否意味着该函数结束了执行并返回了值?

来自 tokio.rs 的确切引用是:

The async fn definition looks like a regular synchronous function, but operates asynchronously. Rust transforms the async fn at compile time into a routine that operates asynchronously. Any calls to .await within the async fn yield control back to the thread. The thread may do other work while the operation processes in the background.

最佳答案

事情还没有结束,只是暂停了。当 future 再次被轮询时,它将继续。

这是一个例子:

use std::future::Future;
use std::task::{Context, Poll};

async fn bar() {
    // Force to yield back to the caller.
    let mut yielded = false;
    std::future::poll_fn(move |_| {
        if !yielded {
            yielded = true;
            Poll::Pending
        } else {
            Poll::Ready(())
        }
    })
    .await;
}

async fn foo() {
    println!("before");
    bar().await;
    println!("after");
}

fn main() {
    let waker = futures::task::noop_waker();
    let mut context = Context::from_waker(&waker);

    let mut future = Box::pin(foo());
    // First, poll the future once.
    assert_eq!(future.as_mut().poll(&mut context), Poll::Pending);
    // Now the future is paused at the `.await` inside `bar()`. Poll it again so it completes.
    assert_eq!(future.as_mut().poll(&mut context), Poll::Ready(()));
}

Playground .

通常,Waker注册到 future 以便在发生某个事件时再次轮询,然后调度程序在事件发生时轮询它。例如,如果您在 tokio 中进行 I/O,则为您的 future 提供的唤醒器将注册它,以便在 I/O 准备就绪时再次轮询。

关于asynchronous - tokio async rust 上的 Yield 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75163822/

相关文章:

rust - Rust Playground和本地计算机中reqwest示例的错误

ios - 具有异步图像加载的自调整 UICollectionView 单元格

.net - 如果其中一个作业出现异常,Async.Parallel 是否会取消所有作业?

rust - Rust在给定一定范围的数字的情况下实现了一个简单的质数集合

rust - 如何在转义序列中使用变量?

cookies - 在与 Hyper 的交易之间保留 cookie

java - myLooper() 在异步任务期间不会退出

javascript - 等到 Jquery 中的 await/async 返回

asynchronous - 如果某些情况发生,则完成 future

rust - tokio是多线程的吗?