有界限的通道
有界限的同步通道可讓 send 阻擋現行執行緒:
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::sync_channel(3);
thread::spawn(move || {
let thread_id = thread::current().id();
for i in 1..10 {
tx.send(format!("Message {i}")).unwrap();
println!("{thread_id:?}: sent Message {i}");
}
println!("{thread_id:?}: done");
});
thread::sleep(Duration::from_millis(100));
for msg in rx.iter() {
println!("Main: got {msg}");
}
}
- 呼叫
send會阻塞目前執行緒,直到管道有空間接收新訊息為止。如果沒有東西讀取管道內容,執行緒可能會無限期遭到阻塞。 - 如果管道已關閉,對
send的呼叫就會取消,並顯示錯誤 (所以會傳回Result)。接收器遭捨棄時,管道就會關閉。 - 大小為零的受限管道稱為「會合管道」。每項傳送作業都會阻塞目前執行緒,直到其他執行緒呼叫
read為止。