gpt4 book ai didi

multithreading - 如何在线程中改变 self ?

转载 作者:行者123 更新时间:2023-11-29 08:18:07 25 4
gpt4 key购买 nike

<分区>

我正在编写一个应用程序,该应用程序应循环读取串口(如观察程序)并向其写入命令。

主线程只能写,创建的线程只能读。

我在这里创建了一个简单的示例来重现我的问题。 tx_thread 循环读取串口,在一定条件下通过 MPSC channel 发送消息。 rx_thread 寻找消息;当它处理任何可用的东西时,它也应该改变结构的当前状态。

use std::sync::mpsc;
use std::thread;
use std::time::Duration;

// this will also implement Drop trait to wait threads to
// be finished (message will be Enum instead of number in this case)

#[derive(Debug)]
struct MyStruct {
num: u32,
tx_thread: Option<thread::JoinHandle<()>>,
rx_thread: Option<thread::JoinHandle<()>>,
}

impl MyStruct {
fn new() -> MyStruct {
MyStruct {
num: 0,
tx_thread: None,
rx_thread: None,
}
}

fn start(&mut self) {
let (tx, rx) = mpsc::channel();

// tx thread will read from serial port infinitely,
// and send data to mpsc channel after certain condition
// to be processed.
let tx_thread = thread::spawn(move || {
let mut i = 0;

loop {
tx.send(i).unwrap();
i += 1;
thread::sleep(Duration::from_secs(1));
}
});

// after this will receive message, it will start
// processing and mutate `self` state if needed.
let rx_thread = thread::spawn(move || loop {
let num = rx.recv().unwrap();
println!("{:?}", num);

/* here, how do I save `num` to `self`? */

thread::sleep(Duration::from_secs(1));
});

self.tx_thread = Some(tx_thread);
self.rx_thread = Some(rx_thread);
}
}

fn main() {
let mut s = MyStruct::new();
s.start();
thread::sleep(Duration::from_secs(999999));
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com