Since Rust uses the model of message passing (same as 202203021733) as a mean of thread synchronisation, a channel must be established for the threads to communicate with each other. The standard library std::sync::mpsc
(mpsc
stand for multiple producer single consumer#) provides the function mpsc::channel
that could create a channel, which will define transmitter(s) (the one that sends messages) and receiver (the one that receives messages). The return type will be a tuple, the first element represents transmitter(s), the second element represents receiver. Combining with #202207171541, we can send a message from a thread (via transmitter’s method send
) to the main thread (via receiver’s method recv
or try_recv
).
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let message = String::from("hi");
tx.send(message).unwrap(); // proper error handling irl
});
let received = rx.recv().unwrap(); // proper error handling irl
println!("Got: {}", received); // Output: Got: hi
Note: If for some reason a receiver has been dropped, send
will return an error. Handle it properly.
Note: recv
will block the main thread’s execution until the message arrived. An error will return if all transmitters connected to the channel have been closed.
Note: try_recv
is like recv
but without waiting. If it doesn’t get the message at the time, it will simply return an error that need to either unwrap
or handled properly. It will not block the execution of the main thread.
We can share the channel created among multiple threads by cloning the transmitter.
let (tx, rx) = mpsc::channel();
let tx1 = tx.clone();
thread::spawn(move || {
let message = String::from("hi");
tx1.send(message).unwrap(); // proper error handling irl
});
let tx2 = tx.clone();
thread::spawn(move || {
let message = String::from("world");
tx2.send(message).unwrap(); // proper error handling irl
});
for received in rx {
println!("Got: {}", received);
}
Note that we can iterate through rx
, the receiver, in a for
loop in order to print out or obtain message(s) from multiple transmitters.