pub struct Latch { /* private fields */ }Expand description
A synchronization primitive that can be released exactly once, notifying all
associated Gates. This is intended for one-shot notifications or
barriers in asynchronous contexts.
§Simple example
use strut_sync::{Gate, Latch};
// Make a latch
let latch = Latch::new();
// Derive a gate from it
let gate = latch.gate();
// Spawn an asynchronous task
tokio::spawn(async move {
// Perform some asynchronous work
println!("This will print first");
// Signal completion
latch.release();
});
// Wait for the completion signal
gate.opened().await;
println!("Asynchronous task completed!")§Full example
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use strut_sync::{Gate, Latch};
use pretty_assertions::assert_eq;
// Make a latch
let latch = Latch::new();
// Derive any number of gates from it
let gate_a = latch.gate();
let gate_b = latch.gate();
let gate_c = gate_b.clone();
// Create a marker
let marker = Arc::new(AtomicU8::new(0));
// Spawn tasks that increment the marker
tokio::spawn(increment_marker(gate_a, marker.clone()));
tokio::spawn(increment_marker(gate_b, marker.clone()));
tokio::spawn(increment_marker(gate_c, marker.clone()));
// Give the tasks a chance to start waiting
tokio::task::yield_now().await;
// Nothing should have happened yet
assert_eq!(marker.load(Ordering::Relaxed), 0);
// Release the latch
latch.release();
// Give the tasks a chance to wake up
tokio::task::yield_now().await;
// Marker should have been increased three times by now
assert_eq!(marker.load(Ordering::Relaxed), 3);
// Helper function
async fn increment_marker(gate: Gate, marker: Arc<AtomicU8>) {
// Wait for the gate to open
gate.opened().await;
// Increment the marker
marker.fetch_add(1, Ordering::Relaxed);
}Implementations§
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Latch
impl RefUnwindSafe for Latch
impl Send for Latch
impl Sync for Latch
impl Unpin for Latch
impl UnwindSafe for Latch
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more