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.
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");}