Rust 如何向特定线程发送消息?
我需要创建一些线程,其中一些线程将一直运行,直到它们的runner变量值被更改。这是我的最小代码Rust 如何向特定线程发送消息?,rust,Rust,我需要创建一些线程,其中一些线程将一直运行,直到它们的runner变量值被更改。这是我的最小代码 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 thr
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());
}
看起来我能够在1秒后将日志运行程序线程中的log\u runner\u ref
设置为false
。有没有一种方法可以用一些名称/ID或类似的东西来标记踏板,并使用其特定的标记(名称/ID)向特定的线程发送消息
如果我理解正确,那么
let(tx,rx)=mpsc::channel()
可用于同时向所有线程发送消息,而不是向特定线程发送消息。我可以在消息中发送一些标识符,每个线程都会寻找自己的标识符来决定是否对接收到的消息采取行动,但我希望避免广播效果。MPSC代表多个生产者、单个消费者。因此,不,您不能单独使用它向所有线程发送消息,因为为此,您必须能够复制使用者。有用于此的工具,但选择它们需要的信息比“MPMC”或“SPMC”多一点
老实说,如果您可以依赖通道进行消息传递(在某些情况下这是一个坏主意),那么您可以为每个线程创建一个通道,在线程外部分配ID,并使用与线程关联的ID保留一个HashMap
而不是Vec
Receiver
可以移动到线程中(如果T
实现Send
),因此您可以直接将其移动到线程中
然后,您将发送者
放在外面,并向其发送内容:-)mpsc
不是用于广播的,它是多个制作者和单个消费者(特定的一个),因此它可以完全按照您的要求执行。