Untitled

 avatar
unknown
plain_text
2 years ago
2.9 kB
1
Indexable
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use std::thread::JoinHandle;
use std::time::Duration;

struct SingleThreadExecutor<T: Send + 'static > {
    sender: Mutex<Sender<Option<T>>>,
    close: Mutex<bool>,
    sender_close: Mutex<Sender<i32>>,
}

impl<T: Send + 'static + Fn()->() > SingleThreadExecutor<T> {
    fn new() -> (Arc<Self>, Option<JoinHandle<()>>) {
        let (sender, receiver) = channel::<Option<T>>();
        let (sender_close, receiver_close) = channel::<i32>();
        let joinhandle = std::thread::spawn(move || {
            let mut i = 0;
            let mut join = false;
            loop {
                if let Ok(j) = receiver_close.try_recv() {
                    //join = true;
                    //i = receiver.len();
                    break;
                }
                match receiver.recv() {
                    Ok(Some(x)) => {
                        x();
                    },
                    Ok(None) => {
                        println!("Eseguo stop");

                        break;
                    },
                    Err(_) => {
                        println!("ciao");
                        // Gestisci l'errore di ricezione
                        break;
                    }
                }
            }
        });

        let executor = SingleThreadExecutor {
            sender: Mutex::new(sender),
            close: Mutex::new(false),
            sender_close: Mutex::new(sender_close),
        };


        (Arc::new(executor), Some(joinhandle))
    }

    fn submit(&self, t: T) -> Option<()> {
        let res = self.sender.lock().unwrap();
        let state = self.close.lock().unwrap();
        if *state {
            return None;
        }
        (*res).send(Some(t)).unwrap();
        Some(())
    }

    fn close(&self) {
        let mut state = self.close.lock().unwrap();
        *state = true;
    }

    fn join(&self){
        //let state = self.sender_close.lock().unwrap();
        //state.send(1).unwrap();
        let cc = self.sender.lock().unwrap();
        (*cc).send(None).unwrap();
    }
}

fn main() {
    let (r, y) = SingleThreadExecutor::new();
    let mut join = Vec::new();

    let r1 = r.clone();
    join.push(std::thread::spawn(move || {
        for i in 0..1000 {
            println!("Invio task {}", i);
            r1.submit(move || { println!("Task {} completato", i); std::thread::sleep(Duration::from_secs(1)); });
        }
    }));

    let r2 = r.clone();
    join.push(std::thread::spawn(move || {
        std::thread::sleep(Duration::from_micros(0));
        println!("Invio stop");
        r2.join();
    }));

    join.push(y.unwrap());

    for handle in join {
        handle.join().unwrap();
    }
}
Editor is loading...