关闭频道,就像在 Go 中一样
Closing a Channel, like in Go
Rust 是否有 "closing" 通道的方法,similar to what is available in Go?
想法是迭代通道(持续接收)直到通道指示它不会产生更多值。
use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;
fn main() {
let data = Arc::new(Mutex::new(0u32));
let (tx, rx) = mpsc::channel::<u32>();
{
let (data, tx) = (data.clone(), tx.clone());
thread::spawn(move || {
for _ in 0..10 {
let mut data = data.lock().unwrap();
*data += 1;
tx.send(*data).unwrap();
}
// *** How could I close the channel here, to signal the work is done?
});
}
// *** How can I detect a closed channel here? Pattern matching?
for _ in 0..10 {
let x = rx.recv().unwrap();
println!("{}", x);
}
}
当所有发件人都掉线后,频道将关闭。在你的代码中,你克隆并给每个线程一个,当线程结束时,它们会按原样下降。最后一个发送者在主线程中,您应该在生成所有线程后立即将其删除:drop(tx)
.
最后,最简单的接收方式是这样,在之后drop(tx)
。
for elt in rx {
/* */
}
这个循环在通道关闭时结束。
Rust 是否有 "closing" 通道的方法,similar to what is available in Go?
想法是迭代通道(持续接收)直到通道指示它不会产生更多值。
use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;
fn main() {
let data = Arc::new(Mutex::new(0u32));
let (tx, rx) = mpsc::channel::<u32>();
{
let (data, tx) = (data.clone(), tx.clone());
thread::spawn(move || {
for _ in 0..10 {
let mut data = data.lock().unwrap();
*data += 1;
tx.send(*data).unwrap();
}
// *** How could I close the channel here, to signal the work is done?
});
}
// *** How can I detect a closed channel here? Pattern matching?
for _ in 0..10 {
let x = rx.recv().unwrap();
println!("{}", x);
}
}
当所有发件人都掉线后,频道将关闭。在你的代码中,你克隆并给每个线程一个,当线程结束时,它们会按原样下降。最后一个发送者在主线程中,您应该在生成所有线程后立即将其删除:drop(tx)
.
最后,最简单的接收方式是这样,在之后drop(tx)
。
for elt in rx {
/* */
}
这个循环在通道关闭时结束。