Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created February 26, 2024 17:22
Show Gist options
  • Save fancellu/92e8d5cb2312f2accfbe1cae62bb1912 to your computer and use it in GitHub Desktop.
Save fancellu/92e8d5cb2312f2accfbe1cae62bb1912 to your computer and use it in GitHub Desktop.
Rust tokio demo of Notify usage
use std::sync::Arc;
use tokio::sync::Notify;
use tokio::time::sleep;
use tokio::time::Duration;
// Notify can be thought of a Semaphore with 0 permits
async fn order_packages(package_delivered: Arc<Notify>) {
sleep(Duration::from_secs(2)).await;
println!("Company: Find package");
sleep(Duration::from_secs(2)).await;
println!("Company: Ship package");
sleep(Duration::from_secs(3)).await;
println!("Company: Package delivered");
package_delivered.notify_one();
}
async fn grab_packages(package_delivered: Arc<Notify>) {
println!("Buyer: Waiting for package");
package_delivered.notified().await;
println!("Buyer: Grab package");
sleep(Duration::from_secs(3)).await;
println!("Buyer: Package delivered");
}
#[tokio::main]
async fn main() {
let package_delivered_arc = Arc::new(Notify::new());
let order_packages_handle = tokio::spawn(order_packages(package_delivered_arc.clone()));
let grab_packages_handle = tokio::spawn(grab_packages(package_delivered_arc.clone()));
order_packages_handle.await.unwrap();
grab_packages_handle.await.unwrap();
}
@fancellu
Copy link
Author

Output

Buyer: Waiting for package
Company: Find package
Company: Ship package
Company: Package delivered
Buyer: Grab package
Buyer: Package delivered

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment