如何将消息发送到特定线程?

时间:2019-09-10 10:35:10

标签: rust

我需要创建一些线程,其中一些线程将在其运行器变量值更改之前运行。这是我的最小代码。

use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

fn main() {
    let mut log_runner = Arc::new(Mutex::new(true));
    println!("{}", *log_runner.lock().unwrap());
    let mut threads = Vec::new();

    {
        let mut log_runner_ref = Arc::clone(&log_runner);
        // log runner thread
        let handle = thread::spawn(move || {
            while *log_runner_ref.lock().unwrap() == true {
                // DO SOME THINGS CONTINUOUSLY
                println!("I'm a separate thread!");
            }
        });
        threads.push(handle);
    }

    // let the main thread to sleep for x time
    thread::sleep(Duration::from_millis(1));
    // stop the log_runner thread
    *log_runner.lock().unwrap() = false;
    // join all threads
    for handle in threads {
        handle.join().unwrap();
        println!("Thread joined!");
    }
    println!("{}", *log_runner.lock().unwrap());
}

看起来我可以在log_runner_ref 1秒后在日志运行程序线程中设置false。有没有一种方法可以用一些名称/ ID或类似名称标记胎面,并使用其特定标记(名称/ ID)将消息发送到特定线程?

如果我对它的理解正确,那么let (tx, rx) = mpsc::channel();可用于同时向所有线程而不是特定线程发送消息。我可以随消息一起发送一些标识符,并且每个线程都将寻找自己的标识符来决定是否对接收到的消息采取行动,但是我想避免广播效应。

1 个答案:

答案 0 :(得分:1)

MPSC代表多个生产者,一个消费者。因此,不能,您不能单独使用 向所有线程发送消息,因为为此您必须能够复制使用者。有 个工具,但是选择它们不仅需要“ MPMC”或“ SPMC”,还需要更多信息。

老实说,如果您可以依靠渠道进行消息传递(在某些情况下这是个坏主意),则可以为每个线程创建一个渠道,在线程之外分配ID,并保留一个{{1} },而不是HashMap以及与线程相关联的ID。 Vec可以移入线程(如果Receiver<T>实现Send,则它实现T),因此您可以从字面上Send进入线程。

然后您将move放在外面并向其中发送内容:-)