有什么办法可以关闭`tokio :: runtime :: current_thread :: Runtime`吗?

时间:2018-12-12 23:03:24

标签: rust rust-tokio

我正在使用tokio::runtime::current_thread::Runtime,并且希望能够运行以后并在同一线程中停止反应堆。页面上的示例未显示如何停止运行时。我有什么办法吗?

1 个答案:

答案 0 :(得分:0)

如果使用block_on,则将来完成时,运行时将自动关闭:

use std::time::{Duration, Instant};
use tokio::{prelude::*, runtime::current_thread, timer::Delay}; // 0.1.15

fn main() {
    let mut runtime = current_thread::Runtime::new().expect("Unable to create the runtime");

    let two_seconds_later = Instant::now() + Duration::from_secs(2);

    runtime
        .block_on({
            Delay::new(two_seconds_later)
                .inspect(|_| eprintln!("future complete"))
        })
        .expect("Unable to run future");
}

如果您需要取消未来,则可以创建将导致未来poll成功的内容。这是这种包装程序的一个非常简单的版本(可能不是很出色):

use std::{
    sync::{Arc, Mutex},
    thread,
    time::{Duration, Instant},
};
use tokio::{prelude::*, runtime::current_thread, timer::Delay}; // 0.1.15

fn main() {
    let mut runtime = current_thread::Runtime::new().expect("Unable to create the runtime");

    let a_long_time = Instant::now() + Duration::from_secs(3600);
    let future = Delay::new(a_long_time).inspect(|_| eprintln!("future complete"));
    let (future, cancel) = Cancelable::new(future);

    let another_thread = thread::spawn(|| {
        eprintln!("Another thread started");
        thread::sleep(Duration::from_secs(2));
        eprintln!("Another thread canceling the future");
        cancel();
        eprintln!("Another thread exiting");
    });

    runtime.block_on(future).expect("Unable to run future");

    another_thread.join().expect("The other thread panicked");
}

#[derive(Debug)]
struct Cancelable<F> {
    inner: F,
    info: Arc<Mutex<CancelInfo>>,
}

#[derive(Debug, Default)]
struct CancelInfo {
    cancelled: bool,
    task: Option<task::Task>,
}

impl<F> Cancelable<F> {
    fn new(inner: F) -> (Self, impl FnOnce()) {
        let info = Arc::new(Mutex::new(CancelInfo::default()));
        let cancel = {
            let info = info.clone();
            move || {
                let mut info = info.lock().unwrap();
                info.cancelled = true;
                if let Some(task) = &info.task {
                    task.notify();
                }
            }
        };
        let me = Cancelable { inner, info };
        (me, cancel)
    }
}

impl<F> Future for Cancelable<F>
where
    F: Future<Item = ()>,
{
    type Item = F::Item;
    type Error = F::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let mut info = self.info.lock().unwrap();

        if info.cancelled {
            Ok(Async::Ready(()))
        } else {
            let r = self.inner.poll();

            if let Ok(Async::NotReady) = r {
                info.task = Some(task::current());
            }

            r
        }
    }
}