// threads3.rs
// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a hint.
use std::sync::mpsc;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
struct Queue {
length: u32,
first_half: Vec<u32>,
second_half: Vec<u32>,
}
impl Queue {
fn new() -> Self {
Queue {
length: 10,
first_half: vec![1, 2, 3, 4, 5],
second_half: vec![6, 7, 8, 9, 10],
}
}
}
fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
let qc = Arc::new(q);
let qc1 = Arc::clone(&qc);
let qc2 = Arc::clone(&qc);
let tx1 = tx.clone();
let tx2 = tx.clone();
thread::spawn(move || {
for val in &qc1.first_half {
println!("sending {:?}", val);
tx1.send(*val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
thread::spawn(move || {
for val in &qc2.second_half {
println!("sending {:?}", val);
tx2.send(*val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
}
fn main() {
let (tx, rx) = mpsc::channel();
let queue = Queue::new();
let queue_length = queue.length;
send_tx(queue, tx);
let mut total_received: u32 = 0;
for received in rx {
println!("Got: {}", received);
total_received += 1;
}
println!("total numbers received: {}", total_received);
assert_eq!(total_received, queue_length)
}
tx2.send(*val).unwrap();
这里为啥要unwrap啊
1
共 2 条评论, 1 页
评论区
写评论因为send发送消息的操作可能会失败。如果rx对方已经挂掉了,这消息就无法发出去,所以send函数通过一个Result返回值会告诉你rx还在不在(Ok等于在,Err等于不在)。
在这里如果unwrap()发现有Err错误的情况,你的程序就会panic崩溃。不写unwrap就不知道有问题了,不过代码还能运行起来。在生产级别的代码里,unwrap不应该使用,最好通过match匹配器好好处理可能出现的错误。
这应该是简单的错误处理,因为
send
返回的是Result,如果出现错误,对其unwrap
可以让进程直接退出。