Advertisement
NLinker

Non blocking stdin

Jul 10th, 2019
467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.96 KB | None | 0 0
  1. // type something and hit enter
  2. // from https://stackoverflow.com/a/55201400/5066426
  3.  
  4. use std::io;
  5. use std::sync::mpsc;
  6. use std::sync::mpsc::Receiver;
  7. use std::sync::mpsc::TryRecvError;
  8. use std::{thread, time};
  9.  
  10. fn main() {
  11.     let stdin_channel = spawn_stdin_channel();
  12.     loop {
  13.         match stdin_channel.try_recv() {
  14.             Ok(key) => println!("Received: {}", key),
  15.             Err(TryRecvError::Empty) => println!("Channel empty"),
  16.             Err(TryRecvError::Disconnected) => panic!("Channel disconnected"),
  17.         }
  18.         sleep(1000);
  19.     }
  20. }
  21.  
  22. fn spawn_stdin_channel() -> Receiver<String> {
  23.     let (tx, rx) = mpsc::channel::<String>();
  24.     thread::spawn(move || loop {
  25.         let mut buffer = String::new();
  26.         io::stdin().read_line(&mut buffer).unwrap();
  27.         tx.send(buffer).unwrap();
  28.     });
  29.     rx
  30. }
  31.  
  32. fn sleep(millis: u64) {
  33.     let duration = time::Duration::from_millis(millis);
  34.     thread::sleep(duration);
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement