'Get Mutex protected value in Coroutine from none-coroutine threads without mpsc?
How to get Mutex protected value in Coroutine from none-coroutine threads in Rust. Without using mpsc.
struct S1 {
value: Arc<tokio::sync::Mutex<f64>>,
}
impl S1 {
fn start(&self) {
let v = self.value.clone();
RT.spawn(async move {
loop {
let lk = v.lock().await;
*lk += 1.0;
drop(lk);
// sleep 1s
}
});
//sleep 5s
let lk = self.value.lock() //`start` is not an async function, so you can't call self.value.lock().await here.
}
}
Solution 1:[1]
You should use tokio::sync::Mutex::blocking_lock() for locking a tokio mutex outside of async context.
fn start(&self) {
let v = self.value.clone();
RT.spawn(async move {
loop {
let lk = v.lock().await;
*lk += 1.0;
drop(lk);
// sleep 1s
}
});
// sleep 5s
let lk = self.value.blocking_lock();
// ...
}
However note that you should prefer std::sync::Mutex as long as you don't need to hold the lock across .await points.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chayim Friedman |
