Search code examples
multithreadingrustrust-tokio

rust tokio::spawn await after mutexguard


I cant place a async function after i lock a mutex. Example 2 works, while example 1 doenst. Why is that. I already disposed of temp, so why is it causing a problem

let temp = Arc::new(Mutex::new(0));
tokio::spawn(async move {
        let temp = temp.lock().unwrap();
        drop(temp);
        async_func().await
    });
tokio::spawn(async move {
        async_func().await;
        let temp = temp.lock().unwrap();
        drop(temp);
    });
future cannot be sent between threads safely future created by async block is not `Send` Help: within `impl futures_util::Future<Output = ()>`, the trait `std::marker::Send` is not implemented for `std::sync::MutexGuard<'_, i32>` Note: future is not `Send` as this value is used across an await Note: required by a bound in `tokio::spawn

Solution

  • You can use a block instead of drop.

    let handle = tokio::spawn(async move {
        {
            let temp = temp.lock().unwrap();
        }
        async_func().await
    });
    

    This is a bug (57478, 87309), so the drop version will work when 97331 is merged.