|
120 | 120 | //! });
|
121 | 121 | //! rx.recv();
|
122 | 122 | //! ```
|
| 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 | +//! ``` |
123 | 169 |
|
124 | 170 | // A description of how Rust's channel implementation works
|
125 | 171 | //
|
|
0 commit comments