multithreading - rust tokio::spawn 在 mutexguard 之后等待

标签 multithreading rust rust-tokio

锁定互斥锁后我无法放置异步函数。示例 2 有效,而示例 1 则有效。这是为什么。我已经处理掉了 temp,为什么它会导致问题

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

最佳答案

您可以使用 block 代替drop

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

这是一个错误( 5747887309 ),因此 drop 版本将在 97331 时运行。已合并。

关于multithreading - rust tokio::spawn 在 mutexguard 之后等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76149897/

相关文章:

rust - 有什么办法可以关闭 `tokio::runtime::current_thread::Runtime` 吗?

python - 无法捕获线程程序中的异常

python - 在 Python-3.x 中使用最大 CPU 功率进行多处理

serialization - Solana Rust 程序 HashMap<string, u64>

rust - std中的async/await功能是否可以替代tokio?

asynchronous - rust 东京 : calling async function from sync closure

python - 当多个子进程使用 `queue.Queue`进行访问时, `concurrent.futures.ProcessPoolExecutor`是线程安全的吗?

线程中的 Java 线程

rust - 如何从特征对象中获取对具体类型的引用?

winapi - 如何使用 winapi crate 为 Windows 制作托盘图标?