pub struct Latch<S: RelaxStrategy> { /* private fields */ }Expand description
A lightweight, memory-efficient synchronization primitive for asynchronous Rust code.
Latch is a synchronization primitive that allows multiple tasks to wait for a signal
that unlocks them all simultaneously. It’s designed with minimal memory overhead,
using only a single usize for its internal state.
When the Latch is open, calling all waiting methods is lock-free and wait-free
§Memory Layout
The Latch struct is marked with #[repr(transparent)] ensuring it has the same
memory layout as a single AtomicUsize, making it extremely lightweight.
§Type Parameters
S- The relaxation strategy used when spinning on the internal lock. Must implement theRelaxStrategytrait from thespincrate.
§Examples
Basic usage:
use latch::{Latch, spin::Spin};
use std::sync::Arc;
let latch = Arc::new(Latch::<Spin>::new());
let latch_clone = latch.clone();
// Spawn a task to wait on the latch
let task = tokio::spawn(async move {
println!("Waiting for latch...");
latch_clone.wait().await;
println!("Latch opened!");
});
// Open the latch, releasing any waiting tasks
latch.open();Multiple waiters:
use latch::{Latch, spin::Spin};
use std::sync::Arc;
let latch = Arc::new(Latch::<Spin>::new());
let mut handles = vec![];
// Spawn multiple waiters
for i in 0..10 {
let latch_clone = latch.clone();
handles.push(tokio::spawn(async move {
println!("Task {i} waiting");
latch_clone.wait().await;
println!("Task {i} resumed");
}));
}
// Open the latch, releasing all waiters at once
latch.open();
// Wait for all tasks to complete
for handle in handles {
handle.await.unwrap();
}Synchronous waiting (with the std feature):
use latch::{Latch, spin::Spin};
use std::sync::Arc;
use std::thread;
let latch = Arc::new(Latch::<Spin>::new());
let latch_clone = latch.clone();
// Spawn a thread that will wait synchronously
let thread_handle = thread::spawn(move || {
println!("Thread waiting");
latch_clone.wait_sync();
println!("Thread resumed");
});
// Open the latch, releasing the waiting thread
latch.open();Implementations§
Trait Implementations§
Source§impl<S: RelaxStrategy> Drop for Latch<S>
impl<S: RelaxStrategy> Drop for Latch<S>
impl<S: RelaxStrategy> Send for Latch<S>
impl<S: RelaxStrategy> Sync for Latch<S>
Auto Trait Implementations§
impl<S> !Freeze for Latch<S>
impl<S> RefUnwindSafe for Latch<S>where
S: RefUnwindSafe,
impl<S> Unpin for Latch<S>where
S: Unpin,
impl<S> UnwindSafe for Latch<S>where
S: UnwindSafe,
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