Advertisement
Guest User

Untitled

a guest
Jan 11th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.10 KB | None | 0 0
  1. use std::sync::mpsc::{Sender};
  2. use std::sync::mpsc;
  3. use std::sync::{Mutex, Arc};
  4. use std::{thread, time};
  5.  
  6. #[derive(Debug)]
  7. struct Inf {
  8.     data: String,
  9.     pos: u8,
  10. }
  11.  
  12. fn main() {
  13.     let (send, recv) = mpsc::channel();
  14.  
  15.     let wttr_send = send.clone();
  16.     thread::spawn(move || {
  17.         get_wttr(wttr_send);
  18.     });
  19.  
  20.     let time_send = send.clone();
  21.     thread::spawn(move || {
  22.         get_time(time_send);
  23.     });
  24.  
  25.     let time = Arc::new(Mutex::new(String::new()));
  26.     let timecpy = time.clone();
  27.  
  28.     let wttr = Arc::new(Mutex::new(String::new()));
  29.     let wttrcpy = wttr.clone();
  30.  
  31.     thread::spawn(move || {
  32.         loop {
  33.             let s = recv.recv().unwrap();
  34.             println!("update: {:?}", s);
  35.             match s.pos {
  36.                 0 => {
  37.                     // time
  38.                     let mut timecpy = timecpy.lock().unwrap();
  39.                     timecpy.clear();
  40.                     timecpy.push_str(&s.data);
  41.                 },
  42.                 1 => {
  43.                     // weather
  44.                     let mut wttrcpy = wttrcpy.lock().unwrap();
  45.                     wttrcpy.clear();
  46.                     wttrcpy.push_str(&s.data);
  47.                 }
  48.                 _ => {},
  49.             }
  50.         }
  51.     });
  52.  
  53.     let mut finalmsg = String::new();
  54.  
  55.     loop {
  56.         // final loop that puts everything together
  57.         finalmsg.clear();
  58.         finalmsg.push_str(&format!("{} ", wttr.lock().unwrap()));
  59.         finalmsg.push_str(&format!("{} ", time.lock().unwrap()));
  60.         println!("finalmsg: {}", finalmsg);
  61.         thread::sleep(time::Duration::from_secs(1));
  62.     }
  63. }
  64.  
  65. fn get_wttr(tx: Sender<Inf>) {
  66.     loop {
  67.         let wttr = Inf {
  68.             data: "sunny".to_string(),
  69.             pos: 1,
  70.         };
  71.         tx.send(wttr).unwrap();
  72.         thread::sleep(time::Duration::from_secs(5));
  73.     }
  74. }
  75.  
  76. fn get_time(tx: Sender<Inf>) {
  77.     loop {
  78.         let wttr = Inf {
  79.             data: "11:11".to_string(),
  80.             pos: 0,
  81.         };
  82.         tx.send(wttr).unwrap();
  83.         thread::sleep(time::Duration::from_secs(1));
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement