gpt4 book ai didi

multithreading - Rust 中的后台工作线程和同步

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

我正在尝试编写一个简单的库,它有一个后台工作线程,在调用库函数时处理命令。

我在 C 语言中通常采用的方式是拥有一个全局信号量句柄,工作程序会在该句柄上进行阻塞。这些函数会在发送命令后给出信号量,此时工作人员将解除阻塞等......还有其他方法,但这只是一个例子。

我有几个关于如何使用 Rust 实现类似功能的问题。

  1. 如何防止线程在创建线程的函数返回后关闭?例如,线程会在我调用 init() 时创建,但会在 init() 返回时退出,如何防止这种情况发生?

  2. 如何在工作线程和函数调用之间建立全局同步方法?我正在考虑使用 channel ,但如何从线程访问 rx 以及从不同函数访问多个 tx?例如 send_cmd_a(), send_cmd_b() 到同一个线程

我要完成的伪代码:

static (tx, rx) = mpsc::channel(); //how to do something like this?

fn init() {
thread::spawn(|| {
loop {
let cmd = rx.recv().unwrap(); //blocks till there is data
//process data....
if cmd == "exit" {
return;
}
}
});
}

fn send_cmd_a() {
//Do a bunch of other stuff...
tx.send("cmd_a").unwrap();
}

fn exit() {
tx.send("exit").unwrap();
}

我是否必须创建一个封装所有这些的大对象,从而拥有同步机制? (仍然没有回答问题 #1)

在 Rust 中做这样的事情的首选方法是什么?

最佳答案

我想我找到了一种无需使用全局变量即可在 Rust 中实现我想要的功能的方法。

struct Device {
sender: Sender<u8>, //other stuff
}

trait New {
fn new() -> Self;
}

trait SendCommand {
fn send_command(&self, u8);
}

impl New for Device {
fn new() -> Device {
let (tx, rx) = channel();
let device = Device { sender: tx };
thread::spawn(move || {
loop {
let cmd = rx.recv().unwrap();
println!("Command: {}", cmd); //process commands here
}
});
return device;
}
}

impl SendCommand for Device {
fn send_command(&self, cmd: u8) {
self.sender.send(cmd).unwrap();
}
}

fn main() {
let dev = Device::new(); //create the device
for i in 0..10 {
dev.send_command(i); //send commands
sleep(Duration::from_millis(50));
}
loop {}
}

关于multithreading - Rust 中的后台工作线程和同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47917343/

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