rust / intermediate
Snippet
Thread-Based Concurrency with std::thread and Channels
Rust's std::thread module enables native OS thread creation, and mpsc (multi-producer, single-consumer) channels provide safe communication between threads. The channel consists of a transmitter (tx) and receiver (rx). The spawn function creates a new thread, and move allows the closure to take ownership of captured variables (tx in this case). Messages sent through the channel are guaranteed to be delivered without data races. The receiver iterator blocks until messages are available, making it ideal for coordinating between threads. This approach to concurrency is explicit and type-safe - the compiler ensures no messages are lost due to type mismatches.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
use std::thread;use std::sync::mpsc;use std::time::Duration;fn main() {let (tx, rx) = mpsc::channel();let handle = thread::spawn(move || {for i in 1..=5 {println!("Thread: sending {}", i);tx.send(i).unwrap();thread::sleep(Duration::from_millis(100));}});for received in rx.iter().take(5) {println!("Main: received {}", received);}handle.join().unwrap();println!("Thread completed successfully");}
Breakdown
1
use std::thread;
Import thread module for spawning native OS threads
2
use std::sync::mpsc;
Import mpsc (multi-producer single-consumer) channel primitives
3
let (tx, rx) = mpsc::channel();
Create a channel pair: transmitter and receiver endpoints
4
let handle = thread::spawn(move || {
Spawn new thread, move transfers tx ownership into the closure
5
for i in 1..=5 {
Loop 5 times sending incrementing integers
6
tx.send(i).unwrap();
Send value through channel, unwrap handles send errors
7
thread::sleep(Duration::from_millis(100));
Simulate work with 100ms pause between sends
8
for received in rx.iter().take(5) {
Iterate over channel with take(5) to process exactly 5 messages
9
println!("Main: received {}", received);
Print each received value in the main thread
10
handle.join().unwrap();
Wait for spawned thread to complete, unwrap join result
11
println!("Thread completed successfully");
Confirmation message after thread finishes