Created
October 23, 2021 04:08
-
-
Save lkevinzc/586fefd0ed88f82d94d2dd98b407a2f1 to your computer and use it in GitHub Desktop.
Snippets
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::{Barrier, Notify}; | |
use tokio::time::{sleep, Duration}; | |
#[tokio::main] | |
async fn main() { | |
let barrier = Arc::new(Barrier::new(10)); | |
let all_ready_notify = Arc::new(Notify::new()); | |
let notify_receiver = all_ready_notify.clone(); | |
for i in 0..10 { | |
tokio::spawn(communicate( | |
i as f64, | |
barrier.clone(), | |
all_ready_notify.clone(), | |
)); | |
} | |
notify_receiver.notified().await; | |
println!("proceed"); | |
} | |
async fn communicate(i: f64, barrier: Arc<Barrier>, all_ready_notify: Arc<Notify>) { | |
let wait = i / 10.; | |
println!("random connections costing {} seconds", wait); | |
sleep(Duration::from_secs_f64(wait)).await; | |
let wait_result = barrier.wait().await; | |
if wait_result.is_leader() { | |
all_ready_notify.notify_one(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment