锁定互斥锁后我无法放置异步函数。示例 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
});
关于multithreading - rust tokio::spawn 在 mutexguard 之后等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76149897/