首页 > 解决方案 > Rust-PyO3 在从 python 调用异步函数后创建死锁/变得无响应

问题描述

lib.rs
#[pyclass]
struct Server {}

#[pymethods]
impl Server {
    #[new]
    fn new() -> Self {
        Self {}
    }

    fn start(mut self_: PyRefMut<Self>, test: &PyAny) {


        let f = pyo3_asyncio::into_future(test);
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let x = f.unwrap().await;
            match &x {
                Ok(_) => (),
                Err(v) => println!("{}", v),
            }
        });
    }
}

#[pymodule]
pub fn roadrunner(py: Python<'_>, m: &PyModule) -> PyResult<()> {
    m.add_class::<Server>()?;
    pyo3_asyncio::try_init(py);
    Ok(())
}

#index.py
import rust_package

async def h():
    print("hhh")


print("Hello world")
s = roadrunner.Server()
s.start(h)

以上是我在项目中使用的 python 和 rust 文件。我正在尝试将异步函数作为参数传递给我的 rust lib,然后使用 tokio 运行时调用它。当我执行我的 python 文件时,我遇到了死锁,因为甚至^C没有退出它。

请让我知道如何正确等待 rust 中的 python 函数。

提前致谢。

标签: pythonasynchronousrustrust-tokiopyo3

解决方案


推荐阅读