有界通道

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

use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let (tx, rx) = mpsc::sync_channel(3);

    thread::spawn(move || {
        let thread_id = thread::current().id();
        for i in 1..10 {
            tx.send(format!("Message {i}")).unwrap();
            println!("{thread_id:?}: sent Message {i}");
        }
        println!("{thread_id:?}: done");
    });
    thread::sleep(Duration::from_millis(100));

    for msg in rx.iter() {
        println!("Main: got {msg}");
    }
}
  • 调用 send 将阻塞当前线程,直到通道中有足够的空间放置新消息。如果无人从通道读取数据,线程会被无限期地阻塞。
  • 如果通道关闭,调用 send 将中止并返回错误(这就是它会返回 Result 的原因)。当接收器被丢弃时,通道将关闭。
  • 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.