From 767d0ed71c9ba5d3d4647af620a16920cf91e392 Mon Sep 17 00:00:00 2001 From: jikstra Date: Thu, 29 Apr 2021 21:43:37 +0200 Subject: [PATCH] Use easier readme example using channels --- README.md | 15 ++++++++------- examples/readme_example.rs | 22 +++++++++------------- 2 files changed, 17 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 3acc3a7..c357769 100644 --- a/README.md +++ b/README.md @@ -8,18 +8,19 @@ A simple easy to use wrapper around Ctrl-C signal. ## Example usage ```rust -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +use std::sync::mpsc::channel; +use ctrlc; fn main() { - let running = Arc::new(AtomicBool::new(true)); - let r = running.clone(); + let (tx, rx) = channel(); + ctrlc::set_handler(move || { - r.store(false, Ordering::SeqCst); + tx.send(()).expect("Could not send signal on channel.") }).expect("Error setting Ctrl-C handler"); + println!("Waiting for Ctrl-C..."); - while running.load(Ordering::SeqCst) {} - println!("Got it! Exiting..."); + rx.recv().expect("Could not receive from channel."); + println!("Got it! Exiting..."); } ``` diff --git a/examples/readme_example.rs b/examples/readme_example.rs index a1b229c..f068b19 100644 --- a/examples/readme_example.rs +++ b/examples/readme_example.rs @@ -7,21 +7,17 @@ // notice may not be copied, modified, or distributed except // according to those terms. -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use std::thread; -use std::time; +use std::sync::mpsc::channel; +use ctrlc; fn main() { - let running = Arc::new(AtomicBool::new(true)); - let r = running.clone(); + let (tx, rx) = channel(); + ctrlc::set_handler(move || { - r.store(false, Ordering::SeqCst); - }) - .expect("Error setting Ctrl-C handler"); + tx.send(()).expect("Could not send signal on channel.") + }).expect("Error setting Ctrl-C handler"); + println!("Waiting for Ctrl-C..."); - while running.load(Ordering::SeqCst) { - thread::sleep(time::Duration::from_millis(10)); - } - println!("Got it! Exiting..."); + rx.recv().expect("Could not receive from channel."); + println!("Got it! Exiting..."); }