use std::{
fmt,
time::{Duration, Instant},
};
use crate::{
Error, Result,
context::{self, Execution},
wait::{NotifyResult, WaitBegin, WaitCell, WaitRegistration, WakeCause},
};
use vthread_stack::ParkToken;
#[path = "parking_wait.rs"]
mod parking_wait;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParkOutcome {
Ready,
TimedOut,
Cancelled,
Closed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnparkResult {
Woke,
Stored,
Closed,
}
pub struct Parker {
pub(crate) wait: WaitCell,
}
impl Parker {
pub fn park(&self) -> Result<ParkOutcome> {
self.park_deadline(None)
}
pub fn park_timeout(&self, timeout: Duration) -> Result<ParkOutcome> {
let deadline = Instant::now()
.checked_add(timeout)
.ok_or(Error::DeadlineOverflow)?;
self.park_deadline(Some(deadline))
}
pub fn park_until(&self, deadline: Instant) -> Result<ParkOutcome> {
self.park_deadline(Some(deadline))
}
fn park_deadline(&self, deadline: Option<Instant>) -> Result<ParkOutcome> {
self.park_with(deadline, |_, _| Ok(()))
}
pub(crate) fn park_after_checkpoint(&self, execution: &Execution) -> Result<ParkOutcome> {
let handoff = if execution.owns_synchronization_wait(&self.wait) {
WaitHandoff::TaskResident
} else {
WaitHandoff::Shared
};
park_wait::<false, false, _>(execution, &self.wait, None, handoff, |_, _| Ok(()))
}
pub(crate) fn park_registered<G>(
&self,
register: impl FnOnce(ParkToken, &WaitRegistration) -> Result<G>,
) -> Result<ParkOutcome> {
self.park_with(None, register)
}
fn park_with<G>(
&self,
deadline: Option<Instant>,
register: impl FnOnce(ParkToken, &WaitRegistration) -> Result<G>,
) -> Result<ParkOutcome> {
let mounted = context::current().ok_or(Error::OutsideVThread)?;
let execution = mounted.execution()?;
execution.data.check()?;
park_wait::<true, false, _>(
execution,
&self.wait,
deadline,
WaitHandoff::Shared,
|token, registration| register(token, registration.expect("shared wait registration")),
)
}
}
pub(crate) fn park_wait_after_checkpoint<const PLAIN_READY: bool, const PERMIT_READY: bool>(
wait: &WaitCell,
execution: &Execution,
) -> Result<ParkOutcome> {
park_wait::<PLAIN_READY, PERMIT_READY, _>(
execution,
wait,
None,
WaitHandoff::TaskResident,
|_, _| Ok(()),
)
}
#[derive(Clone, Copy)]
enum WaitHandoff {
Shared,
TaskResident,
}
fn park_wait<const PLAIN_READY: bool, const PERMIT_READY: bool, G>(
execution: &Execution,
wait: &WaitCell,
deadline: Option<Instant>,
handoff: WaitHandoff,
register: impl FnOnce(ParkToken, Option<&WaitRegistration>) -> Result<G>,
) -> Result<ParkOutcome> {
vthread_stack::check_suspend().map_err(Error::from)?;
let policy = &execution.data;
let unmasked = policy.masked() == 0;
let inherited_deadline = policy.deadline().filter(|_| unmasked);
let inherited_timeout = inherited_deadline
.is_some_and(|inherited| deadline.is_none_or(|explicit| inherited <= explicit));
let deadline = deadline.into_iter().chain(inherited_deadline).min();
let begin = match handoff {
WaitHandoff::Shared => wait
.begin(
execution.id,
execution.task_key(),
execution.hub(),
deadline,
)?
.map_registration(Some),
WaitHandoff::TaskResident => wait
.begin_resident(
execution.id,
execution.task_key(),
execution.hub(),
deadline,
)?
.map_registration(|()| None),
};
match begin {
WaitBegin::Immediate(cause) => selected(cause, inherited_timeout),
WaitBegin::Park {
request,
registration,
} => selected(
parking_wait::park::<PLAIN_READY, PERMIT_READY, _>(
execution,
wait,
request,
registration,
register,
)?,
inherited_timeout,
),
}
}
impl fmt::Debug for Parker {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_struct("Parker").finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct Unparker {
wait: WaitCell,
}
impl Unparker {
pub fn unpark(&self) -> UnparkResult {
match self.wait.notify() {
NotifyResult::Woke => UnparkResult::Woke,
NotifyResult::Stored => UnparkResult::Stored,
NotifyResult::Closed => UnparkResult::Closed,
}
}
pub fn cancel(&self) -> bool {
self.wait.cancel()
}
pub fn close(&self) -> bool {
self.wait.close()
}
pub fn is_closed(&self) -> bool {
self.wait.is_closed()
}
}
impl fmt::Debug for Unparker {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Unparker")
.field("closed", &self.is_closed())
.finish_non_exhaustive()
}
}
pub fn park_pair() -> (Parker, Unparker) {
let wait = WaitCell::new();
(Parker { wait: wait.clone() }, Unparker { wait })
}
fn selected(cause: WakeCause, inherited_timeout: bool) -> Result<ParkOutcome> {
match cause {
WakeCause::Ready => Ok(ParkOutcome::Ready),
WakeCause::TimedOut if inherited_timeout => Err(Error::DeadlineExceeded),
WakeCause::TimedOut => Ok(ParkOutcome::TimedOut),
WakeCause::Cancelled => Ok(ParkOutcome::Cancelled),
WakeCause::InheritedCancelled => Err(Error::Cancelled),
WakeCause::Closed => Ok(ParkOutcome::Closed),
}
}
#[cfg(test)]
#[path = "parking_test.rs"]
mod parking_test;
#[cfg(test)]
#[path = "parking_deadline_test.rs"]
mod parking_deadline_test;