In Rust we often want to process data on multiple threads, and then return values from each thread. Each thread could open a file, or perform an expensive computation.
With the sync mpsc functions, we have a multi-producer single-consumer framework. So multiple threads can produce data, and one thread can consume it.
This example creates an array of four values, and then processes each value on a separate thread. Then each thread returns its result, and they are received in main()
.
use std::sync::mpsc::channel; use std::thread; fn main() { let values = [0, 1, 2, 3]; // Step 1: create a channel. let (send, recv) = channel(); // Step 2: loop over the values, and clone the sender. for value in values { let send_clone = send.clone(); // Step 3: spawn a thread for each value, compute a result, and send it. thread::spawn(move || { send_clone.send((value, value + 10)).unwrap(); }); } // Step 4: receive all sent values. for _ in values { if let Ok(result) = recv.recv() { println!("{} -> {}", result.0, result.1); } } }0 -> 10 2 -> 12 3 -> 13 1 -> 11
With mpsc, we can pass any kind of data to the threads, and then send any kind of data back. This gives us an effective way to process data on many threads, providing great performance gains.