Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.9 kB
4
Indexable
Never
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<T>>,
    joinhandle: JoinHandle<()>,
    close: Mutex<bool>,
}

impl<T: Send + 'static + Fn()->()> SingleThreadExecutor<T>{

    fn new() -> Self{

        let (sender, receiver) = channel::<T>();
        let res = std::thread::spawn(move || {
           loop {
               let s : T = receiver.recv().unwrap();
               s();

           }
        });

        SingleThreadExecutor{
            sender: Mutex::new(sender),
            joinhandle: res,
            close: Mutex::new(false),
        }


    }

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

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

    fn join(&self){


        /*
        let t : T = move || self.joinhandle.join().unwrap();
        self.submit(t);*/
        //self.joinhandle.join().unwrap();
    }
}

fn main() {
    let r = Arc::new(SingleThreadExecutor::new());

    let mut join = Vec::new();

    let r1 = r.clone();

    join.push(thread::spawn(move || {
        for i in 0..10 {
            let state = r1.sender.lock().unwrap();
            state.send(move ||{println!("Task completato {}", i); std::thread::sleep(Duration::from_secs(1))});
            drop(state);
        }

        }));

    let r2 = r.clone();

    join.push(std::thread::spawn(move || {
        std::thread::sleep(Duration::from_secs(2));
        r2.close();
    }));

    for i in join{
        i.join().unwrap();
    }


}