问题描述
我正在制作一个 Python 模块,用 Rust 编写,使用 pyo3,它将:
到目前为止,我的代码是这样的:
use std::thread;
use pyo3::prelude::*;
#[pyclass]
struct CountWatcher {
// The number of the GPIO pin we'll be watching
// Can't be read from Python
pin: u8,// How many times the pin changed state
// Can be read from Python
#[pyo3(get)]
count: u128,// Thread handle
t: thread::JoinHandle<()>,}
#[pymethods]
impl CountWatcher {
#[new]
fn new(pin: u8) -> Self {
let t = thread::spawn(|| {
loop {
// This is where the code that reads the GPIO pin,and increments count will eventually go
println!("Test");
std::thread::sleep(std::time::Duration::from_secs(1));
}
});
Self {
pin,count: 0,t: t,}
}
}
#[pymodule]
fn countwatcher(_py: Python,m: &PyModule) -> PyResult<()> {
m.add_class::<CountWatcher>()?;
Ok(())
}
此代码有效,但我遇到的问题是以某种方式获取对线程内实例的引用,以便我可以更新 count
,同时仍然让 Python 随时检查 count
。
我认为这样的事情会起作用,但它没有:
fn new(pin: u8) -> Arc<Self> {
let mut inst = Self {
pin,t: None,};
let mut inst_1 = Arc::new(inst);
let mut inst_2 = inst_1.clone();
let t = thread::spawn(move || {
loop {
inst_1.count += 1;
std::thread::sleep(std::time::Duration::from_secs(1));
}
});
inst_2.t = Some(t);
inst_2
}
请注意,我必须将结构体的 t
类型转换为 Option<thread::JoinHandle()>>
,因为在这里,我需要在创建线程之前创建实例。此外,我的 new
方法现在返回一个 Arc<Self>
而不仅仅是 Self
,我不确定我是否可以这样做。
我也尝试使用 Arc<Mutex<CountWatcher>>
,但随后我需要从 new 返回 Arc<Mutex<CountWatcher>>
,或者返回 inst_2.lock()
,这只会永久锁定它。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)