sync_channel Zero Capacity Rendezvous
A sync_channel with capacity zero has no buffer, so every send blocks until the receiver takes the value, turning each message into a synchronous handoff.
Code
use std::sync::mpsc::sync_channel;
use std::thread;
use std::time::Duration;
fn main() {
// 容量 0:没有缓冲区,每次 send 都要等 recv 到场,形成会合握手
let (tx, rx) = sync_channel::<u32>(0);
let producer = thread::spawn(move || {
let mut delivered = Vec::new();
for msg in [1, 2, 3] {
tx.send(msg).expect("receiver alive");
delivered.push(msg); // 能走到这里说明对端已取走上一个值
}
delivered
});
for i in 0..3 {
thread::sleep(Duration::from_millis(20));
let value = rx.recv().expect("sender alive");
println!("recv {} -> value {value}", i + 1);
}
let delivered = producer.join().expect("producer panicked");
println!("producer delivered: {delivered:?}");
}What the code does
Structurally, expect the function main and nothing else.
Iteration happens inside for msg in [1, 2, 3] — everything outside it runs once.
Points of care
- Nothing arrives from a registry; the language ships every API used.
Applying it
Entry signature: fn main()
Running the file prints a marker per step: recv, producer delivered:.
Statements that carry the weight
let producer = thread::spawn(move || {
let mut delivered = Vec::new();
for msg in [1, 2, 3] {
tx.send(msg).expect("receiver alive");
delivered.push(msg); // 能走到这里说明对端已取走上一个值
}
delivered
});
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
FAQ
- What does sync_channel Zero Capacity Rendezvous print when run?
- The script runs standalone; its 2 labeled outputs include `recv`, `producer delivered:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.