Function tokio_util::loom::sync::mpsc::sync_channel

1.0.0 · source ·
pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Receiver<T>)
Expand description

Creates a new synchronous, bounded channel. All data sent on the SyncSender 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 SyncSender can be cloned to send to the same channel multiple times, but only one Receiver is supported.

Like asynchronous channels, if the Receiver is disconnected while trying to send with the SyncSender, the send method will return a SendError. Similarly, If the SyncSender 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);