创建一个容量受限的信道,即对它一次能容纳多少信息有一个限制
//可以缓存一条消息
let (s, r) = bounded(1);
例子:
use crossbeam_channel::bounded;
use std::thread;
use std::time::Duration;
fn main() {
//创建一个无限制容量的通道
let (s,r) = bounded(1);
//向通道发送一条消息
s.send("one").unwrap();
thread::spawn(move || {
println!("等待发送");
s.send("two").unwrap();
println!("发送成功");
});
thread::sleep(Duration::from_secs(1));
//接收通道的消息
println!("读取第一条消息");
assert_eq!(r.recv(), Ok("one"));
println!("读取第二条消息,当第一条消息消费完后,线程内的消息才能发送");
assert_eq!(r.recv(), Ok("two"));
}
简易图
一个特殊情况是零容量通道,它不能容纳任何消息。相反,发送和接收操作必须同时出现,以便配对并将消息传递过去。
//不能缓存消息,必须方送方和接收方同时可以完成
let (s, r) = bounded(0);
例子
use crossbeam_channel::bounded;
use std::thread;
use std::time::Duration;
fn main() {
//创建一个无限制容量的通道
let (s,r) = bounded(0);
thread::spawn(move || {
println!("等待发送");
s.send("one").unwrap();
println!("发送成功");
});
thread::sleep(Duration::from_secs(1));
//接收通道的消息
assert_eq!(r.recv(), Ok("one"));
}
简易图