在阅读 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(()));
}
通常,Waker
注册到 future 以便在发生某个事件时再次轮询,然后调度程序在事件发生时轮询它。例如,如果您在 tokio 中进行 I/O,则为您的 future 提供的唤醒器将注册它,以便在 I/O 准备就绪时再次轮询。
关于asynchronous - tokio async rust 上的 Yield 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75163822/