pub struct WaitableCompletion { /* private fields */ }Expand description
A completion signal for synchronizing async operations.
This struct provides a thread-safe mechanism for one thread to signal completion while another thread waits for that signal with optional timeout. It handles mutex poisoning gracefully, preferring progress over panic.
§Thread Safety
All methods are safe to call from multiple threads. The implementation uses:
- An atomic boolean for lock-free completion checks
- A mutex + condvar for efficient blocking waits
- Poison recovery to avoid panics in Drop contexts
§Example
use std::time::Duration;
use std::thread;
let completion = WaitableCompletion::new();
// Spawn a thread that signals completion after a delay
let completion_clone = completion.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(10));
completion_clone.signal();
});
// Wait for completion with timeout
match completion.wait_timeout(Duration::from_secs(1)) {
Ok(()) => println!("Operation completed"),
Err(e) => println!("Timed out: {e}"),
}Implementations§
Source§impl WaitableCompletion
impl WaitableCompletion
Sourcepub fn new_completed() -> Self
pub fn new_completed() -> Self
Creates a new completion signal in the completed state.
Useful when initializing a sender that has no pending async operations.
Sourcepub fn signal(&self)
pub fn signal(&self)
Signals completion and wakes all waiting threads.
This method is safe to call multiple times; subsequent calls are no-ops for the atomic flag but will still notify waiting threads.
Sourcepub fn is_complete(&self) -> bool
pub fn is_complete(&self) -> bool
Checks if the operation has completed.
This is a non-blocking, lock-free check using atomic load.
Sourcepub fn reset(&self)
pub fn reset(&self)
Resets the completion state to incomplete.
Call this before starting a new async operation to reuse the signal.
Sourcepub fn wait_timeout(&self, timeout: Duration) -> Result<(), String>
pub fn wait_timeout(&self, timeout: Duration) -> Result<(), String>
Waits for completion with timeout, returning a Result.
This method blocks until either:
- The completion signal is received (returns
Ok(())) - The timeout elapses (returns
Errwith timeout message)
§Poison Recovery
If the mutex is poisoned (e.g., a thread panicked while holding it), this method recovers the guard and continues waiting. This ensures robust behavior even in exceptional circumstances.
§Errors
Returns an error string if the timeout elapses before completion.