Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

asynchronous - rust tokio: calling async function from sync closure

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.

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.

I'm using tokio as stated in the title.

question from:https://stackoverflow.com/questions/65837485/rust-tokio-calling-async-function-from-sync-closure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

There's a section in the documentation for Tokio's Mutex which states the following (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.

Additionally, from Tokio's mini-Redis example:

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...