Bounded Channels

With bounded (synchronous) channels, send() can block the current thread:

  1. use std::sync::mpsc;
  2. use std::thread;
  3. use std::time::Duration;
  4. fn main() {
  5.     let (tx, rx) = mpsc::sync_channel(3);
  6.     thread::spawn(move || {
  7.         let thread_id = thread::current().id();
  8.         for i in 0..10 {
  9.             tx.send(format!("Message {i}")).unwrap();
  10.             println!("{thread_id:?}: sent Message {i}");
  11.         }
  12.         println!("{thread_id:?}: done");
  13.     });
  14.     thread::sleep(Duration::from_millis(100));
  15.     for msg in rx.iter() {
  16.         println!("Main: got {msg}");
  17.     }
  18. }

This slide should take about 8 minutes.

  • Calling send() will block the current thread until there is space in the channel for the new message. The thread can be blocked indefinitely if there is nobody who reads from the channel.
  • A call to send() will abort with an error (that is why it returns Result) if the channel is closed. A channel is closed when the receiver is dropped.
  • A bounded channel with a size of zero is called a “rendezvous channel”. Every send will block the current thread until another thread calls recv().