Function chan::sync [] [src]

pub fn sync<T>(size: usize) -> (Sender<T>, Receiver<T>)

Create a synchronous channel with a possibly empty buffer.

When the size is zero, the buffer is empty and the channel becomes a rendezvous channel. A rendezvous channel blocks send operations until a corresponding receive operation consumes the sent value.

When the size is non-zero, the send operations will only block when the buffer is full. Send operations only unblock when a receive operation removes an element from the buffer.

Values are guaranteed to be received in the same order that they are sent.

The send and receive values returned can be cloned arbitrarily (i.e., multi-producer/multi-consumer) and moved to other threads.

When all senders are dropped, the channel is closed automatically. No more values may be sent on a closed channel. Once a channel is closed and the buffer is empty, all receive operations return None immediately. (If a channel is closed and there are still values in the buffer, then receive operations will retrieve those first.)

When all receivers are dropped, no special action is taken. When the buffer is full, all subsequent send operations will block indefinitely.

Examples

An example of a rendezvous channel:

use std::thread;

let (send, recv) = chan::sync(0);
thread::spawn(move || send.send(5));
assert_eq!(recv.recv(), Some(5)); // blocks until the previous send occurs

An example of a synchronous buffered channel:

let (send, recv) = chan::sync(1);

send.send(5); // doesn't block because of the buffer
assert_eq!(recv.recv(), Some(5));

drop(send); // closes the channel
assert_eq!(recv.recv(), None);