微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我怎样才能制作一个 Rust 结构来在不同的线程中修改自己的值?

如何解决我怎样才能制作一个 Rust 结构来在不同的线程中修改自己的值?

我正在制作一个 Python 模块,用 Rust 编写,使用 pyo3,它将:

  • 运行自己的线程
  • 读取 RaspBerry Pi 上的输入引脚,计算状态改变的次数
  • 让 Python 查询计数器

到目前为止,我的代码是这样的:

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 举报,一经查实,本站将立刻删除。