Skip to content

Commit 5412fda

Browse files
committed
Add examples of how to read from a channel with a timeout, refs #13862
1 parent e7f11f2 commit 5412fda

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/libsync/comm/mod.rs

+46
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,52 @@
120120
//! });
121121
//! rx.recv();
122122
//! ```
123+
//!
124+
//! Reading from a channel with a timeout requires to use a Timer together
125+
//! with the channel. You can use the select! macro to select either and
126+
//! handle the timeout case. This first example will break out of the loop
127+
//! after 10 seconds no matter what:
128+
//!
129+
//! ```no_run
130+
//! use std::io::timer::Timer;
131+
//!
132+
//! let (tx, rx) = channel::<int>();
133+
//! let mut timer = Timer::new().unwrap();
134+
//! let timeout = timer.oneshot(10000);
135+
//!
136+
//! loop {
137+
//! select! {
138+
//! val = rx.recv() => println!("Received {}", val),
139+
//! () = timeout.recv() => {
140+
//! println!("timed out, total time was more than 10 seconds")
141+
//! break;
142+
//! }
143+
//! }
144+
//! }
145+
//! ```
146+
//!
147+
//! This second example is more costly since it allocates a new timer every
148+
//! time a message is received, but it allows you to timeout after the channel
149+
//! has been inactive for 5 seconds:
150+
//!
151+
//! ```no_run
152+
//! use std::io::timer::Timer;
153+
//!
154+
//! let (tx, rx) = channel::<int>();
155+
//! let mut timer = Timer::new().unwrap();
156+
//!
157+
//! loop {
158+
//! let timeout = timer.oneshot(5000);
159+
//!
160+
//! select! {
161+
//! val = rx.recv() => println!("Received {}", val),
162+
//! () = timeout.recv() => {
163+
//! println!("timed out, no message received in 5 seconds")
164+
//! break;
165+
//! }
166+
//! }
167+
//! }
168+
//! ```
123169
124170
// A description of how Rust's channel implementation works
125171
//

0 commit comments

Comments
 (0)