capypad
0 day streak
rust / intermediate
Snippet

Thread Communication with mpsc Channels

Rust's mpsc (multiple producer, single consumer) channels enable safe communication between threads. The channel returns a sender (tx) and receiver (rx). The spawn function creates a new thread, and move makes the closure take ownership of captured variables. recv() blocks until a message is received.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use std::thread;
use std::sync::mpsc;
 
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let message = String::from("Hello from worker thread!");
tx.send(message).unwrap();
});
let received = rx.recv().unwrap();
println!("Main thread received: {}", received);
let (tx2, rx2) = mpsc::channel();
let handle = thread::spawn(move || {
tx2.send(42).unwrap();
});
handle.join().unwrap();
println!("Received number: {}", rx2.recv().unwrap());
}
Breakdown
1
let (tx, rx) = mpsc::channel()
Create a multi-producer single-consumer channel returning transmitter and receiver
2
thread::spawn(move || { ... })
Spawn a new thread, move closure takes ownership of tx
3
tx.send(message).unwrap()
Send the string message through the channel, unwrap handles send error
4
rx.recv().unwrap()
Block and receive the message, unwrap handles channel disconnection error
5
handle.join().unwrap()
Wait for the spawned thread to complete before continuing main thread