pub fn bounded<T>(cap: usize) -> (Sender<T>, Receiver<T>)Expand description
Channel type definition based on features Use crossbeam::channel when crossbeam_channel feature is enabled, otherwise use std::sync::mpsc 基于 features 的 channel 类型定义 启用 crossbeam_channel feature 时使用 crossbeam::channel,否则使用 std::sync::mpsc Creates a channel of bounded capacity.
This channel has a buffer that can hold at most cap messages 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 capacity 1:
use std::thread;
use std::time::Duration;
use crossbeam_channel::bounded;
let (s, r) = bounded(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 crossbeam_channel::bounded;
let (s, r) = bounded(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));