diff options
| author | Jordi Boggiano <j.boggiano@seld.be> | 2014-06-14 00:49:01 +0200 |
|---|---|---|
| committer | Jordi Boggiano <j.boggiano@seld.be> | 2014-06-16 18:26:39 +0200 |
| commit | 5412fdacaf273bf3ce3230a078ff8ad156cc61a2 (patch) | |
| tree | bf32ea4627fc32cff13543cc11bb61ef0549f669 /src/libsync | |
| parent | e7f11f20e5e72a3b22863a9913df94303321a5ce (diff) | |
| download | rust-5412fdacaf273bf3ce3230a078ff8ad156cc61a2.tar.gz rust-5412fdacaf273bf3ce3230a078ff8ad156cc61a2.zip | |
Add examples of how to read from a channel with a timeout, refs #13862
Diffstat (limited to 'src/libsync')
| -rw-r--r-- | src/libsync/comm/mod.rs | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/libsync/comm/mod.rs b/src/libsync/comm/mod.rs index a7523eff04f..842743657a6 100644 --- a/src/libsync/comm/mod.rs +++ b/src/libsync/comm/mod.rs @@ -120,6 +120,52 @@ //! }); //! rx.recv(); //! ``` +//! +//! Reading from a channel with a timeout requires to use a Timer together +//! with the channel. You can use the select! macro to select either and +//! handle the timeout case. This first example will break out of the loop +//! after 10 seconds no matter what: +//! +//! ```no_run +//! use std::io::timer::Timer; +//! +//! let (tx, rx) = channel::<int>(); +//! let mut timer = Timer::new().unwrap(); +//! let timeout = timer.oneshot(10000); +//! +//! loop { +//! select! { +//! val = rx.recv() => println!("Received {}", val), +//! () = timeout.recv() => { +//! println!("timed out, total time was more than 10 seconds") +//! break; +//! } +//! } +//! } +//! ``` +//! +//! This second example is more costly since it allocates a new timer every +//! time a message is received, but it allows you to timeout after the channel +//! has been inactive for 5 seconds: +//! +//! ```no_run +//! use std::io::timer::Timer; +//! +//! let (tx, rx) = channel::<int>(); +//! let mut timer = Timer::new().unwrap(); +//! +//! loop { +//! let timeout = timer.oneshot(5000); +//! +//! select! { +//! val = rx.recv() => println!("Received {}", val), +//! () = timeout.recv() => { +//! println!("timed out, no message received in 5 seconds") +//! break; +//! } +//! } +//! } +//! ``` // A description of how Rust's channel implementation works // |
