Untitled
unknown
plain_text
2 years ago
2.9 kB
3
Indexable
use std::fmt::Debug;use std::ops::Sub;use std::sync::mpsc::{channel, Receiver, Sender};use std::sync::{Arc, Mutex};use std::time::Duration; struct Dispatcher<T: Clone + Send + 'static> { senders: Mutex<Vec<Sender<Msg<T>>>> } struct Subscription<T: Clone + Send + 'static> { receiver: Receiver<Msg<T>> } impl<T: Clone + Send + 'static> Drop for Subscription<T> { fn drop(&mut self) { // Logica personalizzata da eseguire quando la struct viene deallocata // println!("La struct MyStruct sta per essere deallocata"); // Altre azioni da eseguire... } } } #[derive(Clone, Debug)] struct Msg<T: Clone + Send + 'static> { mess: T } impl <T: Clone + Send + 'static> Dispatcher<T> { fn dispatch(&self, msg: Msg<T>) { let mut lock = self.senders.lock().unwrap(); for i in 0..lock.len(){ let res = lock[i].send(msg.clone()); match res { Err(err) => {let _ = lock.remove(i);}, _ => continue } } } fn subscribe(&self) -> Subscription<T> { let mut lock = self.senders.lock().unwrap(); let (sender, receiver) = channel::<Msg<T>>(); lock.push(sender); return Subscription { receiver } } } impl <T: Clone + Send + Debug + 'static> Subscription<T> { fn read(&self) -> Option<Msg<T>> { let rec = self.receiver.recv(); // println!("HA PRINTATO IL VALORE {:?}", rec.clone().unwrap()); match rec.clone() { Err(err) => { None }, x => { println!("HA PRINTATO IL VALORE {:?}", x.clone().unwrap()); Some(x.clone().unwrap()) } } //Some(rec.clone().unwrap()) } } } fn main() { let disp = Arc::new(Dispatcher{ senders: Mutex::new(Vec::new())} ); let disp1 = disp.clone(); //thread principale std::thread::spawn(move || { std::thread::sleep(Duration::new(1, 0)); for i in 0..10 { /* if i == 5 { drop(&disp1); break; }*/ disp1.dispatch(Msg { mess: "prova" }); } }); let disp2 = disp.clone(); let mut threads = Vec::new(); threads.push(std::thread::spawn(move || { let subscr = disp2.subscribe(); for i in 0..10 { //std::mem::drop(subscr.clone()); if i == 5 { drop(&subscr); break; } let res = subscr.read(); //println!("Ciclo {} printa {:?}", i, res.unwrap()); } })); for i in threads{ i.join().unwrap(); } }
Editor is loading...