std::sync::mpmc

Function sync_channel

Source
pub fn sync_channel<T>(cap: usize) -> (Sender<T>, Receiver<T>)
🔬This is a nightly-only experimental API. (mpmc_channel #126840)
Expand description

Creates a new synchronous, bounded channel.

All data sent on the Sender will become available on the Receiver in the same order as it was sent. Like asynchronous channels, the Receiver will block until a message becomes available. sync_channel differs greatly in the semantics of the sender, however.

This channel has an internal buffer on which messages will be queued. bound specifies the buffer size. When the internal buffer becomes full, future sends will block waiting for the buffer to open up. Note that a buffer size of 0 is valid, in which case this becomes “rendezvous channel” where each send will not return until a recv is paired with it.

The Sender can be cloned to send to the same channel multiple times. The Receiver also can be cloned to have multi receivers.

Like asynchronous channels, if the Receiver is disconnected while trying to send with the Sender, the send method will return a SendError. Similarly, If the Sender is disconnected while trying to recv, the recv method will return a RecvError.

§Examples

use std::sync::mpsc::sync_channel;
use std::thread;

let (sender, receiver) = sync_channel(1);

// this returns immediately
sender.send(1).unwrap();

thread::spawn(move || {
    // this will block until the previous message has been received
    sender.send(2).unwrap();
});

assert_eq!(receiver.recv().unwrap(), 1);
assert_eq!(receiver.recv().unwrap(), 2);