Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::sync::mpsc::{Sender};
- use std::sync::mpsc;
- use std::sync::{Mutex, Arc};
- use std::{thread, time};
- #[derive(Debug)]
- struct Inf {
- data: String,
- pos: u8,
- }
- fn main() {
- let (send, recv) = mpsc::channel();
- let wttr_send = send.clone();
- thread::spawn(move || {
- get_wttr(wttr_send);
- });
- let time_send = send.clone();
- thread::spawn(move || {
- get_time(time_send);
- });
- let time = Arc::new(Mutex::new(String::new()));
- let timecpy = time.clone();
- let wttr = Arc::new(Mutex::new(String::new()));
- let wttrcpy = wttr.clone();
- thread::spawn(move || {
- loop {
- let s = recv.recv().unwrap();
- println!("update: {:?}", s);
- match s.pos {
- 0 => {
- // time
- let mut timecpy = timecpy.lock().unwrap();
- timecpy.clear();
- timecpy.push_str(&s.data);
- },
- 1 => {
- // weather
- let mut wttrcpy = wttrcpy.lock().unwrap();
- wttrcpy.clear();
- wttrcpy.push_str(&s.data);
- }
- _ => {},
- }
- }
- });
- let mut finalmsg = String::new();
- loop {
- // final loop that puts everything together
- finalmsg.clear();
- finalmsg.push_str(&format!("{} ", wttr.lock().unwrap()));
- finalmsg.push_str(&format!("{} ", time.lock().unwrap()));
- println!("finalmsg: {}", finalmsg);
- thread::sleep(time::Duration::from_secs(1));
- }
- }
- fn get_wttr(tx: Sender<Inf>) {
- loop {
- let wttr = Inf {
- data: "sunny".to_string(),
- pos: 1,
- };
- tx.send(wttr).unwrap();
- thread::sleep(time::Duration::from_secs(5));
- }
- }
- fn get_time(tx: Sender<Inf>) {
- loop {
- let wttr = Inf {
- data: "11:11".to_string(),
- pos: 0,
- };
- tx.send(wttr).unwrap();
- thread::sleep(time::Duration::from_secs(1));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement