【问题标题】:Background worker thread and synchronization in RustRust 中的后台工作线程和同步
【发布时间】:2017-12-21 03:07:05
【问题描述】:

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

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

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

  1. 一旦创建线程的函数返回,如何防止线程关闭?例如,当我调用init() 时会创建线程,但当init() 返回时会退出,如何防止?

  2. 如何在工作线程和函数调用之间有一个全局同步方法?我正在考虑使用通道,但是如何从线程访问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 中做这种事情的首选方式是什么?

【问题讨论】:

  • 一旦创建线程的函数返回,我如何防止线程关闭——这已经是thread::spawn的行为了。
  • @Shepmaster 你是对的。我弄错了,似乎线程保持打开状态但在程序退出时自动关闭。另外,谢谢你的链接

标签: multithreading rust


【解决方案1】:

我想我找到了一种在 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 {}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    相关资源
    最近更新 更多