Channels

Rust provides asynchronous channels for communication between threads. Channels
allow a unidirectional flow of information between two end-points: the
Sender and the Receiver.

  1. use std::sync::mpsc::{Sender, Receiver};
  2. use std::sync::mpsc;
  3. use std::thread;
  4. static NTHREADS: i32 = 3;
  5. fn main() {
  6. // Channels have two endpoints: the `Sender<T>` and the `Receiver<T>`,
  7. // where `T` is the type of the message to be transferred
  8. // (type annotation is superfluous)
  9. let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();
  10. for id in 0..NTHREADS {
  11. // The sender endpoint can be copied
  12. let thread_tx = tx.clone();
  13. // Each thread will send its id via the channel
  14. thread::spawn(move || {
  15. // The thread takes ownership over `thread_tx`
  16. // Each thread queues a message in the channel
  17. thread_tx.send(id).unwrap();
  18. // Sending is a non-blocking operation, the thread will continue
  19. // immediately after sending its message
  20. println!("thread {} finished", id);
  21. });
  22. }
  23. // Here, all the messages are collected
  24. let mut ids = Vec::with_capacity(NTHREADS as usize);
  25. for _ in 0..NTHREADS {
  26. // The `recv` method picks a message from the channel
  27. // `recv` will block the current thread if there are no messages available
  28. ids.push(rx.recv());
  29. }
  30. // Show the order in which the messages were sent
  31. println!("{:?}", ids);
  32. }