在没有 mpsc 的情况下从 none-协程线程获取协程中的互斥保护值?
Get Mutex protected value in Coroutine from none-coroutine threads without mpsc?
如何从 none-Rust 协程线程中获取协程中的互斥保护值。不使用 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.
}
}
您应该使用 tokio::sync::Mutex::blocking_lock()
在异步上下文之外锁定 tokio 互斥锁。
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();
// ...
}
但是请注意 you should prefer std::sync::Mutex
as long as you don't need to hold the lock across .await
points.
如何从 none-Rust 协程线程中获取协程中的互斥保护值。不使用 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.
}
}
您应该使用 tokio::sync::Mutex::blocking_lock()
在异步上下文之外锁定 tokio 互斥锁。
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();
// ...
}
但是请注意 you should prefer std::sync::Mutex
as long as you don't need to hold the lock across .await
points.