我写了一个简单的方法来查看按顺序返回Tokio的DelayQueue
中的项目。 DelayQueue
具有方法poll_expired
,该方法以task::Context
作为参数。我想在循环中调用poll_explained
,直到Delays
中的所有DelayQueue
实例都超时并由poll_expired
返回并使用Tokio提供的Context
运行。为此,我使用一个函数poll_fn
:
use std::vec::Vec;
use tokio::time::delay_queue::Key;
use tokio::time::{DelayQueue, Duration, Error};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
/// Creates a new future wrapping around a function returning [`Poll`].
fn poll_fn<T, F>(f: F) -> PollFn<F>
where
F: FnMut(&mut Context<'_>) -> Poll<T>,
{
PollFn { f }
}
PollFn
实现Future
的地方:
/// Future for the [`poll_fn`] function.
struct PollFn<F> {
f: F,
}
impl<T, F> Future for PollFn<F>
where
F: FnMut(&mut Context<'_>) -> Poll<T>,
{
type Output = T;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
(&mut self.f)(cx)
}
}
然后,我创建我的函数,该函数将所有到期的Delays
批处理并将其委托给poll_fn
:
macro_rules! ready {
($e:expr $(,)?) => {
match $e {
std::task::Poll::Ready(t) => t,
std::task::Poll::Pending => return std::task::Poll::Pending,
}
};
}
fn poll_expired_batch(
dq: &mut DelayQueue<u32>,
cx: &mut Context<'_>,
) -> Poll<Result<Vec<(u32, u64)>, Error>> {
let mut expired_keys: Vec<(u32, u64)> = Vec::new();
while let Some(res) = ready!(dq.poll_expired(cx)) {
let exp = res?;
let data = exp.get_ref();
expired_keys.push((data.inner, data.when));
}
Poll::Ready(Ok(expired_keys));
}
async fn poll_batch(dq: &mut DelayQueue<u32>) -> Result<Vec<(u32, u64)>, Error> {
poll_fn(|cx| poll_expired_batch(dq, cx)).await;
}
然后在tokio::main
块中,我有以下代码:
#[tokio::main]
async fn main() {
let mut dq: DelayQueue<u32> = DelayQueue::new();
let mut keys: Vec<Key> = Vec::new();
(0..10).map(|i| keys.push(dq.insert(i, Duration::new(1, 0))));
println!("Insertion order");
for key in keys {
println("Key {} inserted");
}
let keys_returned = (poll_batch(&mut dq).await)?;
}
我收到以下错误,但我无法找出错误的含义和解决方法:
error[E0271]: type mismatch resolving `<impl core::future::future::Future as core::future::future::Future>::Output == std::result::Result<std::vec::Vec<(u32, u64)>, tokio::time::error::Error>`
--> examples/delay_q.rs:75:51
|
75 | async fn poll_batch(dq : &mut DelayQueue<u32>) -> Result<Vec<(u32, u64)>, Error>{
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::result::Result`
|
= note: expected type `()`
found type `std::result::Result<std::vec::Vec<(u32, u64)>, tokio::time::error::Error>`
= note: the return type of a function must have a statically known size