Consider this Rust program using channels for message passing. What will it print?
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send(42).unwrap();
});
let received = rx.recv().unwrap();
println!("Received: {}", received);
}Think about how the sender moves ownership of the transmitter into the thread and sends the value.
The sender tx is moved into the spawned thread, which sends the value 42. The receiver rx receives it and prints it.
Choose the correct statement about Rust's std::sync::mpsc channels.
Think about which side of the channel supports cloning for multiple producers or consumers.
In Rust, the sender (tx) can be cloned to allow multiple threads to send messages. The receiver (rx) cannot be cloned.
Examine this Rust code snippet using channels. What error will it produce when compiled?
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
tx.send(10).unwrap();
let val = rx.recv().unwrap();
let val2 = rx.recv().unwrap();
println!("{} {}", val, val2);
}Consider what happens when you try to receive more messages than sent.
Only one message is sent. The first recv() gets 10. The second recv() blocks indefinitely because the sender tx is still in scope (the main thread is blocked on recv(), preventing tx from being dropped), resulting in a deadlock.
Identify the correct fix for the syntax error in this Rust code snippet:
let (tx, rx) = mpsc::channel();
thread::spawn(|| {
tx.send(5).unwrap();
});Think about ownership when moving variables into threads.
The closure needs to take ownership of tx to send the message inside the new thread. Adding move fixes the syntax error.
Given this Rust program using multiple senders, how many messages will the receiver get?
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for i in 0..3 {
let tx_clone = tx.clone();
thread::spawn(move || {
tx_clone.send(i).unwrap();
});
}
drop(tx);
let mut count = 0;
while let Ok(_) = rx.recv() {
count += 1;
}
println!("Received {} messages", count);
}Consider how many senders send messages and when the original sender is dropped.
Three cloned senders each send one message. The original sender is dropped to close the channel. The receiver gets exactly 3 messages.