Skip to content

Instantly share code, notes, and snippets.

@ssrlive
Created June 16, 2024 05:47
Show Gist options
  • Save ssrlive/852eec039dbc5ff3635a317866601e69 to your computer and use it in GitHub Desktop.
Save ssrlive/852eec039dbc5ff3635a317866601e69 to your computer and use it in GitHub Desktop.
tokio::sync::Notify usage
use std::sync::Arc;
use tokio::sync::Notify;
#[tokio::main]
async fn main() {
let notify = Arc::new(Notify::new());
// 注册两个等候者
let notified1 = notify.notified();
let notified2 = notify.notified();
let handle = tokio::spawn({
let notify2 = notify.clone();
async move {
println!("waiting for 1 seconds");
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
println!("sending notifications");
notify2.notify_waiters();
}
});
println!("waiting for notifications");
// 两个等候者的 await 都会直接通过
notified1.await;
notified2.await;
println!("received notifications");
handle.await.unwrap();
}
// output:
//
// waiting for notifications
// waiting for 1 seconds
// sending notifications
// received notifications
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment