Функция has_ budget_ remaining
pub fn has_budget_remaining() -> bool
Доступно только при включённой функции crate
rt.Возвращает true, если у задачи ещё остался бюджет.
Примеры
В этом примере определяется future Timeout, для завершения которого требуется заданное future до истечения указанного времени. Если это условие выполнено, возвращается результат; в противном случае возвращается ошибка, а future отменяется.
Обратите внимание, что future может исчерпать бюджет ещё до проверки тайм-аута. Используя has_budget_remaining, мы можем обнаружить такую ситуацию и гарантировать, что тайм-аут всегда будет проверен.
pub struct Timeout<T> {
future: T,
delay: Pin<Box<Sleep>>,
}
impl<T> Future for Timeout<T>
where
T: Future + Unpin,
{
type Output = Result<T::Output, ()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = Pin::into_inner(self);
let future = Pin::new(&mut this.future);
let delay = Pin::new(&mut this.delay);
// check if the future is ready
let had_budget_before = coop::has_budget_remaining();
if let Poll::Ready(v) = future.poll(cx) {
return Poll::Ready(Ok(v));
}
let has_budget_now = coop::has_budget_remaining();
// evaluate the timeout
if let (true, false) = (had_budget_before, has_budget_now) {
// it is the underlying future that exhausted the budget
ready!(pin!(coop::unconstrained(delay)).poll(cx));
} else {
ready!(delay.poll(cx));
}
return Poll::Ready(Err(()));
}
}
MIT License
Copyright © Tokio Contributors
https://docs.rs/tokio/1.53.1/tokio/task/coop/fn.has_budget_remaining.html