gpt4 book ai didi

asynchronous - rust 东京 : calling async function from sync closure

转载 作者:行者123 更新时间:2023-12-03 11:31:14 25 4
gpt4 key购买 nike

我有以下问题:我正在尝试从 async 函数调用 sync 闭包,但是 sync 闭包 稍后必须调用另一个 async 函数.

我无法进行异步关闭,因为它们目前不稳定:错误[E0658]:异步闭包不稳定

所以我必须以某种方式这样做。

我发现了几个与该问题相关的问题,例如 this ,但是当我尝试实现它时,我收到以下错误:

Cannot start a runtime from within a runtime. 
This happens because a function (like `block_on`)
attempted to block the current thread while the
thread is being used to drive asynchronous tasks.'

这里是 playground link希望能说明我遇到的问题。

我正在使用标题中所述的 tokio。

最佳答案

如错误消息所述,Tokio 不允许您拥有嵌套的运行时。

Tokio 的 Mutex 文档中有一个部分说明如下 ( link):

[It] is ok and often preferred to use the ordinary Mutex from the standard library in asynchronous code. [...] the feature that the async mutex offers over the blocking mutex is that it is possible to keep the mutex locked across an .await point, which is rarely necessary for data.

此外,来自 Tokio 的 mini-Redis示例:

A Tokio mutex is mostly intended to be used when locks need to be heldacross .await yield points. All other cases are usually bestserved by a std mutex. If the critical section does not include anyasync operations but is long (CPU intensive or performing blockingoperations), then the entire operation, including waiting for the mutex,is considered a "blocking" operation and tokio::task::spawn_blockingshould be used.

如果 Mutex 是您在同步调用中唯一需要的 async 东西,最好将其设为阻塞 Mutex。在这种情况下,您可以通过首先调用 try_lock() 将其从 async 代码中锁定,如果失败,则尝试通过 将其锁定在阻塞上下文中spawn_blocking.

关于asynchronous - rust 东京 : calling async function from sync closure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65837485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com