pub fn new_channel<T>(capacity: Option<usize>) -> (Sender<T>, Receiver<T>)Expand description
Creates a multi-producer multi-consumer channel of either bounded or unbounded capacity.
- If
capacityisNone, this channel has a growable buffer that can hold any number of messages at a time. - If
capacityisSome(n), this channel has a buffer that can hold at mostnmessages at a time.
A special case is zero-capacity channel, which cannot hold any messages. Instead, send and receive operations must appear at the same time in order to pair up and pass the message over.
ยงExamples
A channel of unbounded capacity:
use std::thread;
use lambda_channel::channel::new_channel;
let (s, r) = new_channel(None);
// Computes the n-th Fibonacci number.
fn fib(n: i32) -> i32 {
if n <= 1 {
n
} else {
fib(n - 1) + fib(n - 2)
}
}
// Spawn an asynchronous computation.
thread::spawn(move || s.send(fib(20)).unwrap());
assert_eq!(r.recv(), Ok(6765))A channel of capacity 1:
use std::thread;
use std::time::Duration;
use lambda_channel::channel::new_channel;
let (s, r) = new_channel(Some(1));
// This call returns immediately because there is enough space in the channel.
s.send(1).unwrap();
thread::spawn(move || {
// This call blocks the current thread because the channel is full.
// It will be able to complete only after the first message is received.
s.send(2).unwrap();
});
thread::sleep(Duration::from_secs(1));
assert_eq!(r.recv(), Ok(1));
assert_eq!(r.recv(), Ok(2));A zero-capacity channel:
use std::thread;
use std::time::Duration;
use lambda_channel::channel::new_channel;
let (s, r) = new_channel(Some(0));
thread::spawn(move || {
// This call blocks the current thread until a receive operation appears
// on the other side of the channel.
s.send(1).unwrap();
});
thread::sleep(Duration::from_secs(1));
assert_eq!(r.recv(), Ok(1));