|
112 | 112 | //! });
|
113 | 113 | //! rx.recv().unwrap();
|
114 | 114 | //! ```
|
115 |
| -//! |
116 |
| -//! Reading from a channel with a timeout requires to use a Timer together |
117 |
| -//! with the channel. You can use the `select!` macro to select either and |
118 |
| -//! handle the timeout case. This first example will break out of the loop |
119 |
| -//! after 10 seconds no matter what: |
120 |
| -//! |
121 |
| -//! ```no_run |
122 |
| -//! # #![feature(std_misc, old_io)] |
123 |
| -//! use std::sync::mpsc::channel; |
124 |
| -//! use std::old_io::timer::Timer; |
125 |
| -//! use std::time::Duration; |
126 |
| -//! |
127 |
| -//! let (tx, rx) = channel::<i32>(); |
128 |
| -//! let mut timer = Timer::new().unwrap(); |
129 |
| -//! let timeout = timer.oneshot(Duration::seconds(10)); |
130 |
| -//! |
131 |
| -//! loop { |
132 |
| -//! select! { |
133 |
| -//! val = rx.recv() => println!("Received {}", val.unwrap()), |
134 |
| -//! _ = timeout.recv() => { |
135 |
| -//! println!("timed out, total time was more than 10 seconds"); |
136 |
| -//! break; |
137 |
| -//! } |
138 |
| -//! } |
139 |
| -//! } |
140 |
| -//! ``` |
141 |
| -//! |
142 |
| -//! This second example is more costly since it allocates a new timer every |
143 |
| -//! time a message is received, but it allows you to timeout after the channel |
144 |
| -//! has been inactive for 5 seconds: |
145 |
| -//! |
146 |
| -//! ```no_run |
147 |
| -//! # #![feature(std_misc, old_io)] |
148 |
| -//! use std::sync::mpsc::channel; |
149 |
| -//! use std::old_io::timer::Timer; |
150 |
| -//! use std::time::Duration; |
151 |
| -//! |
152 |
| -//! let (tx, rx) = channel::<i32>(); |
153 |
| -//! let mut timer = Timer::new().unwrap(); |
154 |
| -//! |
155 |
| -//! loop { |
156 |
| -//! let timeout = timer.oneshot(Duration::seconds(5)); |
157 |
| -//! |
158 |
| -//! select! { |
159 |
| -//! val = rx.recv() => println!("Received {}", val.unwrap()), |
160 |
| -//! _ = timeout.recv() => { |
161 |
| -//! println!("timed out, no message received in 5 seconds"); |
162 |
| -//! break; |
163 |
| -//! } |
164 |
| -//! } |
165 |
| -//! } |
166 |
| -//! ``` |
167 | 115 |
|
168 | 116 | #![stable(feature = "rust1", since = "1.0.0")]
|
169 | 117 |
|
|
0 commit comments