经过与 rust 编译器长时间较量,无奈败下阵来。寻找 v 友助阵。
下面的代码想实现,单生产者,多消费者模型。通过 channel 传递 String 变量
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let mut txs = vec![];
let mut rxs: Vec<Arc<Mutex<Receiver<String>>>> = Vec::new();
let mut all_recv = vec![];
for i in 0..5 {
let (tx, rx) = channel();
txs.push(tx);
rxs.push(Arc::new(Mutex::new(rx)));
}
let sender = thread::spawn(move || {
for i in 0..1000 {
let tx = &txs[i % 5];
tx.send(i.to_string()).expect("send fail");
}
});
for i in 0..5 {
let rx = &'static rxs[i];
let receiver = thread::spawn(move || loop {
let value = match rx.lock().unwrap().recv() {
Ok(value) => value,
Err(_) => break,
};
});
all_recv.push(receiver);
}
sender.join();
for (_, v) in all_recv.iter().enumerate() {
v.join();
}
}
error: expected `:`, found `rxs`
--> src/main.rs:24:27
|
24 | let rx = &'static rxs[i];
| ^^^ expected `:`
重温了rust程序设计,使用多所有权可以解决编译错误,完整代码如下。如有不完美的地方,欢迎指正
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let mut txs = vec![];
let mut rxs: Vec<Arc<Mutex<Receiver<String>>>> = Vec::new();
let mut all_recv = vec![];
for i in 0..5 {
let (tx, rx) = channel();
txs.push(tx);
rxs.push(Arc::new(Mutex::new(rx)));
}
let sender = thread::spawn(move || {
for i in 0..1000 {
let tx = &txs[i % 5];
tx.send(i.to_string()).expect("send fail");
}
});
for i in 0..5 {
//let rx = &'static rxs[i];
let rx = &rxs[i];
let rx = Arc::clone(rx);
let receiver = thread::spawn(move || loop {
let value = match rx.lock().unwrap().recv() {
Ok(value) => value,
Err(_) => break,
};
println!("{}", value);
});
all_recv.push(receiver);
}
sender.join();
for v in all_recv {
v.join();
}
}