I am look for a primitive that would make two threads wait until an event happens and then continue but if the event already happened then don’t even stop waiting.
I imagine that a watch channel may work but that does not seem very idiomatic.
Pure tokio notify may not work as an event may happen earlier than thread starts waiting for notification. So maybe adding a boolean wrapped in Mutex is necessary. But I want a standard idiomatic solution as I imagine the problem is not new. Basically, I want code similar to the following to work and have no race conditions.
use std::sync::Arc;
use tokio::sync::Notify;
#[tokio::main]
async fn main() {
let notify = Arc::new(Notify::new());
let notify2 = notify.clone();
let notify3 = notify.clone();
println!("sending notification");
notify.notify_waiters();
let handle = tokio::spawn(async move {
notify2.notified().await;
println!("received notification 1");
});
let handle = tokio::spawn(async move {
notify3.notified().await;
println!("received notification 2");
});
// Wait for task to receive notification.
handle.await.unwrap();
}