Home
Map
sync Example (mpsc channel)Use the sync mpsc, multi producer single consumer, functions to process and return data from threads.
Rust
This page was last reviewed on Jul 15, 2023.
Sync. 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.
Example. 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().
Step 1 First we create a channel. This function is referenced from the "use" statement at the top.
Step 2 We loop over the four values in our integer array. We clone the sender so it can be moved into each thread.
Step 3 We create a thread, and process the integer. Then we send the result back through the sender.
Step 4 In a separate loop on the original thread, we receive all the sent values and print them.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 15, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.