有什么办法关机`TOKIO ::运行时:: current_thread :: Runtime`?

问题描述 投票:1回答:1

我使用tokio::runtime::current_thread::Runtime,我希望能够运行一个未来,在同一个线程停止反应堆。页面上的例子并没有说明如何停止运行。有没有什么办法可以做到这一点?

rust rust-tokio
1个回答
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");
}

如果您需要取消以后,你可以创造的东西,会导致未来polls成功。这里是一个非常简单的(也可能不是非常高性能的)这样一个包装的版本:

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
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.