I have been scouring the docs to find a way to call an asynchronous function synchronously. Specifically, I am trying to call tokio::sync::mutex::lock
from a Display
implementation to provide useful information.
This is an example of what I want to be able to do:
struct MyStruct(Mutex<u64>);
impl fmt::Display for MyStruct {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Current Value: {}", self.0.lock().await)
}
}
fn main() {
let s = MyStruct(Mutex::new(8));
println!("{}", s)
}
I could get over it in this case and just avoid it all together, but this seems like a serious limitation which I am running into.
My first thought was to use tokio::task::spawn
and then use the join handle, however, that does not seem to be possible as the join function is itself a future. I would just call poll
on the future returned from the mutex, but I cannot find anywhere how to provide the Context
parameter, which leads me to believe it is an internal executor thing.
When I was digging around I discovered async_std::task::block_on
which seems to do exactly what I need but I would like to stick to Tokio. Am I missing something or is this actually a limitation with the Tokio framework?