rust tokio:从同步关闭调用异步函数 [英] rust tokio: calling async function from sync closure

查看:299
本文介绍了rust tokio:从同步关闭调用异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following problem: I'm trying to call sync closure from async function, but sync closure has to later call another async function.

我无法进行异步关闭,因为它们目前处于不稳定状态: error [E0658]:异步关闭不稳定

I cannot make async closure, because they are unstable at the moment: error[E0658]: async closures are unstable

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

so I have to do it this way somehow.

我发现了几个与此问题相关的问题,例如

I found a couple of questions related to the problem, such as this, but when I tried to implement it, im receiving the following error:

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.'

这是游乐场链接希望可以显示我遇到的问题.

here is playground link which hopefully can show what I'm having problem with.

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

I'm using tokio as stated in the title.

推荐答案

错误消息指出,Tokio不允许您使用嵌套的运行时.

As the error message states, Tokio doesn't allow you to have nested runtimes.

Tokio的 Mutex 文档中有一个部分指出了以下内容(链接):

There's a section in the documentation for Tokio's Mutex which states the following (link):

[没关系]可以,并且通常首选在异步代码中使用标准库中的普通Mutex.[...]异步互斥锁在阻塞互斥锁上提供的功能是可以将互斥锁锁定在 .await 点上,这对于数据来说是很少必要的.

[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的迷你-Redis 示例:

Additionally, from Tokio's mini-Redis example:

Tokio互斥锁主要用于需要持有锁的情况跨 .await 屈服点.其他所有情况通常最佳由标准互斥锁提供服务.如果关键部分不包含任何内容异步操作,但时间较长(CPU密集或执行阻塞操作),然后进行整个操作,包括等待互斥体,被认为是封锁"操作和 tokio :: task :: spawn_blocking 应该使用.

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

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

If the Mutex is the only async thing you need in your synchronous call, it's most likely better to make it a blocking Mutex. In that case, you can lock it from async code by first calling try_lock(), and, if that fails, attempting to lock it in a blocking context via spawn_blocking.

这篇关于rust tokio:从同步关闭调用异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆