Reputation: 427
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.
Upvotes: 3
Views: 4869
Reputation: 2917
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 andtokio::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
.
Upvotes: 2