Skip to content

Add examples of how to read from a channel with a timeout, refs #13862 #14877

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 16, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions src/libsync/comm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be:

timer.oneshot(5000).recv() => { /* ... */ }

(I think)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This failed with error: no rules expected the token '5000' so I kept it out of the select but I moved the Timer creation out of the loop.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that's because of #12902.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yes of course!

//! println!("timed out, no message received in 5 seconds")
//! break;
//! }
//! }
//! }
//! ```

// A description of how Rust's channel implementation works
//
Expand Down