How to lock().await a futures::lock⁠::Mutex on non async code

    let vpn_client: Arc<futures::lock::Mutex<dyn VpnClient>> = ...

    let on_virtual_tun_write = Arc::new(
        move |f: &mut dyn FnMut(&mut [u8]),size: usize|  -> std::result::Result<(), VirtualTunWriteError> {
            let mut buffer = vec![0; size];
            match vpn_client_.lock().await.send(buffer.as_slice())

As you can see in the example above, I have an Arc<futures::lock::Mutex<dyn VpnClient>>. I use it for other things in async code, but there's a library that which accepts on_virtual_tun_write which is not async, , so I cannot lock() this mutex inside of this callback.

How could I lock().await this mutex outside of some async code? And is this a good solution? I cannot use non async Mutex because of the rest of the code.

It depends on where the callback is called. If the callback is called from inside the async context, then you can't, period. If it's outside the async context, you can use block_on on the lock call.

Here async context means any function that has an async fn anywhere above it in the callstack.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.