【问题标题】:New Tokio + dependency with older hyper新的 Tokio + 依赖于旧的 hyper
【发布时间】:2020-02-01 15:55:14
【问题描述】:

我使用的是 tokio 0.2.x,但我需要使用依赖于 hyper 0.12.35 的依赖项。

这会导致SpawnError { is_shutdown: true } 出现恐慌。

我设法以孤立的方式重现了这个:

cargo.toml

[dependencies]
tokio = { version = "0.2.11", features = ["full"] }
hyper = "0.12.35"
futures = "0.1.29"

这是代码:

use hyper::rt;
use futures::future as future01;

fn future_01() -> impl future01::Future<Item = (), Error = ()> {
    future01::ok(())
}

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
    rt::spawn(future_01());
    Ok(())
}

我的依赖在实现中有这个rt::spawn,所以我不能修改它。

理想情况下,我想将rt::spawn 使用的默认执行程序设置为与tokio::main 提供的执行程序相同。这可能吗?

【问题讨论】:

    标签: rust async-await rust-tokio hyper


    【解决方案1】:

    理想情况下,我想将rt::spawn 使用的默认执行程序设置为 与tokio::main 提供的相同。这可能吗?

    不可能,tokio = "0.2.11" 只有实现std::future::Future 才能生成任务,您无法使用futures = "0.1.29" 创建这些任务,您需要使用版本0.3.x 还是需要使用将旧期货转换为新期货的兼容功能 (see OP's Q&A for details)。

    这导致SpawnError { is_shutdown: true } 出现恐慌。

    您正在使用的 Hyper 在内部使用 tokio 运行时,它是 Tokio 的旧版本(它也在您的 Cargo.lock 中,带有较新的版本)。在 Tokio 中,如果没有启动运行时就无法生成任务,因此您需要像这样生成任务:

    fn main() -> Result<(), std::io::Error> {
        rt::run(future_01());
        Ok(())
    }
    

    警告:

    如果您仍想使用 2 个不同的运行时,一个来自新版本,另一个来自旧版本,请不要像下面这样使用它!您需要在单独的线程中运行它们。

    //don't use this code!
    #[tokio::main]
    async fn main() -> Result<(), std::io::Error> {
        rt::run(future_01());
        Ok(())
    }
    

    因为main 是异步函数,rt::run 是阻塞函数(why you shouldn't call long running code inside async fn)

    【讨论】:

      猜你喜欢
      • 2020-03-26
      • 2017-09-11
      • 2014-07-07
      • 2021-12-03
      • 2020-03-29
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多