diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
commit | 36d22d82aa202bb199967e9512281e9a53db42c9 (patch) | |
tree | 105e8c98ddea1c1e4784a60a5a6410fa416be2de /third_party/rust/crossbeam-channel/examples/stopwatch.rs | |
parent | Initial commit. (diff) | |
download | firefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.tar.xz firefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.zip |
Adding upstream version 115.7.0esr.upstream/115.7.0esrupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/crossbeam-channel/examples/stopwatch.rs')
-rw-r--r-- | third_party/rust/crossbeam-channel/examples/stopwatch.rs | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/third_party/rust/crossbeam-channel/examples/stopwatch.rs b/third_party/rust/crossbeam-channel/examples/stopwatch.rs new file mode 100644 index 0000000000..3a7578e00d --- /dev/null +++ b/third_party/rust/crossbeam-channel/examples/stopwatch.rs @@ -0,0 +1,56 @@ +//! Prints the elapsed time every 1 second and quits on Ctrl+C. + +#[cfg(windows)] // signal_hook::iterator does not work on windows +fn main() { + println!("This example does not work on Windows"); +} + +#[cfg(not(windows))] +fn main() { + use std::io; + use std::thread; + use std::time::{Duration, Instant}; + + use crossbeam_channel::{bounded, select, tick, Receiver}; + use signal_hook::consts::SIGINT; + use signal_hook::iterator::Signals; + + // Creates a channel that gets a message every time `SIGINT` is signalled. + fn sigint_notifier() -> io::Result<Receiver<()>> { + let (s, r) = bounded(100); + let mut signals = Signals::new(&[SIGINT])?; + + thread::spawn(move || { + for _ in signals.forever() { + if s.send(()).is_err() { + break; + } + } + }); + + Ok(r) + } + + // Prints the elapsed time. + fn show(dur: Duration) { + println!("Elapsed: {}.{:03} sec", dur.as_secs(), dur.subsec_millis()); + } + + let start = Instant::now(); + let update = tick(Duration::from_secs(1)); + let ctrl_c = sigint_notifier().unwrap(); + + loop { + select! { + recv(update) -> _ => { + show(start.elapsed()); + } + recv(ctrl_c) -> _ => { + println!(); + println!("Goodbye!"); + show(start.elapsed()); + break; + } + } + } +} |