You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pyo3中异步函数自引用的生命周期问题及解决咨询

PyO3异步方法中的生命周期与GIL冲突问题

我编写了如下Rust代码:

use pyo3::prelude::*;
use std::collections::{HashMap, HashSet};
use std::sync::RwLock;

#[pyclass]
struct Rustex {
    map: RwLock<HashMap<String, String>>,
    contexts: RwLock<HashSet<String>>,
}

#[pymethods]
impl Rustex {
    #[new]
    fn new() -> Self {
        Rustex {
            map: RwLock::new(HashMap::new()),
            contexts: RwLock::new(HashSet::new()),
        }
    }

    fn acquire_mutex<'a>(
        &mut self,
        py: Python<'a>,
        mutex_name: String,
        context: String,
    ) -> PyResult<&'a PyAny> {
        pyo3_asyncio::async_std::future_into_py(py, async move {
            let mut map = self.map.write().unwrap();
            Ok(Python::with_gil(|py| py.None()))
        })
    }
}

#[pymodule]
fn rustex(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<Rustex>()?;

    Ok(())
}

编译时出现如下错误:

error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
   --> src/main.rs:27:64
    |
22  |           &mut self,
    |           --------- this data with an anonymous lifetime `'_`...
...
27  |           pyo3_asyncio::async_std::future_into_py(py, async move {
    |  ________________________________________________________________^
28  | |             let mut map = self.map.write().unwrap();
29  | |             Ok(Python::with_gil(|py| py.None()))
30  | |         })
    | |_________^ ...is used here...
    |
note: ...and is required to live as long as `'static` here
   --> src/main.rs:27:9
    |
27  |         pyo3_asyncio::async_std::future_into_py(py, async move {
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: `'static` lifetime requirement introduced by this bound
   --> /Users/shep/.cargo/registry/src/github.com-1ecc6299db9ec823/pyo3-asyncio-0.16.0/src/async_std.rs:318:46
    |
318 |     F: Future<Output = PyResult<T>> + Send + 'static,
    |                                              ^^^^^^^

若将self设置为'static,则会出现GIL相关错误:

error[E0597]: `_ref` does not live long enough
  --> src/main.rs:11:1
   |
11 | #[pymethods]
   | ^^^^^^^^^^^-
   | |          |
   | |          `_ref` dropped here while still borrowed
   | borrowed value does not live long enough
   | argument requires that `_ref` is borrowed for `'static`
   |
   = note: this error originates in the attribute macro `pymethods` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0597]: `gil` does not live long enough
  --> src/main.rs:11:1
   |
11 | #[pymethods]
   | ^^^^^^^^^^^-
   | |          |
   | |          `gil` dropped here while still borrowed
   | borrowed value does not live long enough
   | argument requires that `gil` is borrowed for `'static`
   |
   = note: this error originates in the attribute macro `pymethods` (in Nightly builds, run with -Z macro-backtrace for more info)

我想咨询是否有以下两种解决途径的可行方案:

  • 让self引用无需'static生命周期仍可在异步代码中使用
  • 让GIL的生命周期满足需求

使用的依赖版本如下:

pyo3 = { version = "0.16.5", features = ["extension-module"] }
pyo3-asyncio = { version = "0.16", features = ["attributes", "async-std-runtime"] }
async-std = "1.9"

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:17:01