recv_timeout Bounds Channel Waits
Bound channel waits with recv_timeout, branch on Timeout and Disconnected separately, and probe without waiting using try_recv.
Code
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
// 克隆一个发送端留在主线程:通道不会因工作线程退出而断开
let keep_alive = tx.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(800));
tx.send("late result".into()).unwrap();
});
// recv_timeout:等待有上限,超时返回 RecvTimeoutError 而非永久阻塞
match rx.recv_timeout(Duration::from_millis(100)) {
Ok(msg) => println!("got: {msg}"),
Err(mpsc::RecvTimeoutError::Timeout) => println!("first try: timed out"),
Err(mpsc::RecvTimeoutError::Disconnected) => println!("sender dropped"),
}
// 第二次等待足够长,覆盖慢生产者
match rx.recv_timeout(Duration::from_millis(1500)) {
Ok(msg) => println!("got: {msg}"),
Err(e) => println!("unexpected: {e}"),
}
// try_recv 只探测一次,从不等待;发送端仍存活时空队列返回 Empty
match rx.try_recv() {
Ok(m) => println!("drained: {m}"),
Err(mpsc::TryRecvError::Empty) => println!("try_recv: queue empty"),
Err(mpsc::TryRecvError::Disconnected) => println!("try_recv: channel closed"),
}
drop(keep_alive);
}What the code does
recv_timeout Bounds Channel Waits is built around the function main.
Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Applying it
The run emits 7 labeled sections — got:, first try: timed out, sender dropped, unexpected:, drained:, try_recv: queue empty, try_recv: channel closed — one per step.
Statements that matter
match rx.recv_timeout(Duration::from_millis(1500)) {
Ok(msg) => println!("got: {msg}"),
Err(e) => println!("unexpected: {e}"),
}
match rx.recv_timeout(Duration::from_millis(100)) {
Ok(msg) => println!("got: {msg}"),
Err(mpsc::RecvTimeoutError::Timeout) => println!("first try: timed out"),
Err(mpsc::RecvTimeoutError::Disconnected) => println!("sender dropped"),
}
tx.send("late result".into()).unwrap();
Interactive Tools for This Topic
FAQ
- What does recv_timeout Bounds Channel Waits print when run?
- Execute the whole file; each printed line is prefixed with a label like `got:`, `first try: timed out`, `sender dropped`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.