How to use a Tokio Mutex within a sync and async context?

38 Views Asked by At

I am using a trait from a third party library which does not support async methods.

My state is behind an Arc<tokio::sync::Mutex<T>> and I need to use it within the context of this library.

struct MyStruct {
  state: Arc<tokio::sync::Mutex<usize>>
}

impl Fold for MyStruct {
  fn fold_xyz(&self, node: Node) {
    let state = self.state.blocking_lock();
  }
}

Where the struct is called by the library

async fn fold_thing(state: Arc<Mutex<usize>>) {
  let mut my_struct = MyStruct { state };

  let result = library.globals.set(move || {
    target.fold_with(&mut my_struct)
  }}
}

I tried calling state.blocking_lock() however that results in the error:

Cannot block the current thread from within a runtime. This happens because 
a function attempted to block the current thread while the thread is being
used to drive asynchronous tasks

I don't fully understand why this error is occuring, is it because the the mutex is being used in a closure within an async function?

Or is that because the internals of the third party library also use an async runtime of their own?

0

There are 0 best solutions below