簡體   English   中英

tokio async rust 的 yield 是什么意思?

[英]What is the meaing of yield on tokio async rust?

在閱讀 Tokio rust 文檔時,它談到將控制權交還給線程。 這是否意味着function結束了他的執行並返回了一個值?

tokio.rs 的確切引用是:

async fn 定義看起來像常規的同步 function,但操作是異步的。 Rust 將編譯時的 async fn 轉換為異步操作的例程。 async fn 中對 .await 的任何調用都會將控制權交還給線程。 當操作在后台進行時,線程可能會做其他工作。

您可以將 tokio(和其他異步運行時)視為調度程序,將異步函數視為要完成的任務。 在這種情況下,'yield' 意味着正在運行的任務可以決定暫停執行以將控制權交還給調度程序,以便線程可以用於處理另一個任務(如果有其他任務排隊)。 如果沒有其他任務可用,那么調度程序可能會決定繼續執行之前的任務。 任務沒有結束。 這更像是我們在任務中保存我們的位置,以便我們稍后可以 go 回到它。

因此,當您調用異步 function 時,您實際上是在向調度程序提供一個新任務。 然后,當您使用.await時,您是在告訴調度程序您要等待該任務的結果。 這使得 yield 變得可取,因為在其他任務完成之前我們無能為力,我們希望釋放資源以便在我們等待的同時處理其他任務。

它沒有結束,只是暫停了。 當未來將再次被投票時,它將繼續。

這是一個例子:

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的waker會注冊它,等I/O准備好再輪詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM