[英]How to Use Serial Port in Multiple Threads in Rust?
我正在嘗試在Linux上讀寫我的串行端口以與微控制器通信,而我正在Rust中嘗試這樣做。
用C ++或Python開發時,我的正常模式是有兩個線程:一個線程周期性地通過串行發送請求,另一個線程從緩沖區讀取字節並處理它們。
在Rust中,使用串行包裝箱時我遇到了借閱檢查器的麻煩。 這對我來說是有道理的,但是我不確定在Rust中異步通信接口的設計是什么樣的。 這是我的來源片段:
let mut port = serial::open(&device_path.as_os_str()).unwrap();
let request_temperature: Vec<u8> = vec![0xAA];
thread::spawn(|| {
let mut buffer: Vec<u8> = Vec::new();
loop {
let _bytes_read = port.read(&mut buffer);
// process data
thread::sleep(Duration::from_millis(100));
}
});
loop {
port.write(&request_temperature);
thread::sleep(Duration::from_millis(1000));
}
在Rust中有兩個線程持有可變資源的情況下,如何模擬此功能? 我知道由於此特定示例可以在單個線程中完成,但是我正在考慮最終使用更大的程序,最終將導致多個線程。
您可以將端口包裝在Arc
和Mutex
,然后可以編寫如下內容:
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
struct Port;
impl Port {
pub fn read(&mut self, _v: &mut Vec<u8>) {
println!("READING...");
}
pub fn write(&mut self, _v: &Vec<u8>) {
println!("WRITING...");
}
}
pub fn main() {
let mut port = Arc::new(Mutex::new(Port));
let p2 = port.clone();
let handle = thread::spawn(move || {
let mut buffer: Vec<u8> = Vec::new();
for j in 0..100 {
let _bytes_read = p2.lock().unwrap().read(&mut buffer);
thread::sleep(Duration::from_millis(10));
}
});
let request_temperature: Vec<u8> = vec![0xAA];
for i in 0..10 {
port.lock().unwrap().write(&request_temperature);
thread::sleep(Duration::from_millis(100));
}
handle.join();
}
為了可以在測試機上運行,我用存根類替換了串行端口,減少了睡眠,並用一些有限循環替換了無限循環。
在這種情況下,您實際上可能會希望在某個階段在線程之間進行適當的通信,這時您將要查看std::sync::mpsc::channel
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.