pub struct StopGuard { /* private fields */ }Expand description
Guard allowing to stop blocking operations when dropped.
§Usage
- Instantiate a guard and the paired
StopTokenviaSelf::new()in a future. - Leave the guard as-is inside the future.
- Send the token to a blocking Tokio task (i.e., a
tokio::task::spawn_blocking()closure). - Check the token state periodically via
StopToken::should_stop()in the blocking task; stop the task if it istrue.
§Why this works
If a future is dropped (e.g., by timing it out, selecting between it and another future, etc.),
blocking task(s) spawned inside the future will continue executing indefinitely because Rust / Tokio
don’t provide means to stop threads (which means do exist in some OSes, but are notoriously unsafe to use).
StopGuard provides an app-level solution to this concern. It is a thin non-cloneable wrapper around an Arc,
and StopToken is a (cloneable) Weak reference to it. StopToken::should_stop() checks whether the strong count
for the Arc is zero.
Implementations§
Trait Implementations§
Auto Trait Implementations§
impl Freeze for StopGuard
impl RefUnwindSafe for StopGuard
impl Send for StopGuard
impl Sync for StopGuard
impl Unpin for StopGuard
impl UnwindSafe for StopGuard
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