Created
February 26, 2024 17:22
-
-
Save fancellu/92e8d5cb2312f2accfbe1cae62bb1912 to your computer and use it in GitHub Desktop.
Rust tokio demo of Notify usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
Buyer: Waiting for package
Company: Find package
Company: Ship package
Company: Package delivered
Buyer: Grab package
Buyer: Package delivered