-
Notifications
You must be signed in to change notification settings - Fork 240
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor cancellation system to a separate cancellation token struct …
…and clean up panic code
- Loading branch information
1 parent
bdbb3d0
commit e9d4183
Showing
2 changed files
with
95 additions
and
53 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
use std::{ | ||
sync::{Condvar, Mutex}, | ||
time::Duration, | ||
}; | ||
|
||
/// A cancellation token. | ||
pub(crate) struct CancellationToken { | ||
// The "check" for the cancellation token. Setting this to true will mark the cancellation token as "cancelled". | ||
mutex: Mutex<bool>, | ||
cvar: Condvar, | ||
} | ||
|
||
impl Default for CancellationToken { | ||
fn default() -> Self { | ||
Self { | ||
mutex: Mutex::new(false), | ||
cvar: Condvar::new(), | ||
} | ||
} | ||
} | ||
|
||
impl CancellationToken { | ||
/// Mark the [`CancellationToken`] as cancelled. | ||
/// | ||
/// This is idempotent, and once cancelled, will stay cancelled. Sending it | ||
/// again will not do anything. | ||
pub fn cancel(&self) { | ||
let mut guard = self | ||
.mutex | ||
.lock() | ||
.expect("cancellation token lock should not be poisoned"); | ||
|
||
if !*guard { | ||
*guard = true; | ||
self.cvar.notify_all(); | ||
} | ||
} | ||
|
||
/// Try and check the [`CancellationToken`]'s status. Note that | ||
/// this will not block. | ||
pub fn try_check(&self) -> Option<bool> { | ||
self.mutex.try_lock().ok().map(|guard| *guard) | ||
} | ||
|
||
/// Allows a thread to sleep while still being interruptible with by the token. | ||
/// | ||
/// Returns the condition state after either sleeping or being woken up. | ||
pub fn sleep_with_cancellation(&self, duration: Duration) -> bool { | ||
let guard = self | ||
.mutex | ||
.lock() | ||
.expect("cancellation token lock should not be poisoned"); | ||
|
||
let (result, _) = self | ||
.cvar | ||
.wait_timeout(guard, duration) | ||
.expect("cancellation token lock should not be poisoned"); | ||
|
||
*result | ||
} | ||
} |