Untitled
unknown
plain_text
2 years ago
2.1 kB
6
Indexable
use std::fmt::Debug;
use std::sync::Arc;
use crossbeam::channel::{Receiver, Sender, unbounded};
use std::time::Duration;
struct Dispatcher<T: Send + Clone + 'static>{
sender: Sender<T>,
receiver: Receiver<T>
}
struct Subscription<T: Send + Clone + 'static>{
receiver: Receiver<T>
}
impl<T: Send + Clone + 'static> Dispatcher<T> {
fn new() -> Self{
let (sender, receiver) = unbounded();
return Dispatcher{
sender,
receiver
}
}
fn dispatch(&self, msg: T){
self.sender.send(msg);
}
fn subscribe(&self) -> Subscription<T> {
return Subscription{
receiver: self.receiver.clone()
}
}
}
impl <T: Send + Clone + 'static> Subscription<T>{
fn read(&self) -> Option<T>{
let res = self.receiver.recv().unwrap();
return Some(res);
}
}
fn main() {
let mut threads = Vec::new();
let str = Arc::new(Dispatcher::new());
let s1 = str.clone();
threads.push(std::thread::spawn(move || {
std::thread::sleep(Duration::from_secs(2));
for i in 0..30 {
let s = format!("prova {}", i);
s1.dispatch(s);
}
}));
for i in 0..3 {
let s2 = str.clone();
threads.push(std::thread::spawn(move || {
let s = s2.subscribe();
for j in 0..10 {
let d = s.read();
println!("stampa {:?} al ciclo {} dal thread {}", d, j, i);
}
}));
}
/*
for i in 0..10{
let strcp = str.clone();
threads.push(std::thread::spawn(move || {
if i%2==0 {
strcp.dispatch("prova ");
} else {
let subscriber = strcp.subscribe();
let d = subscriber.read();
println!("{:?} al ciclo {}", d, i);
}
}))
}
*/
for i in threads {
i.join().unwrap();
}
}Editor is loading...