Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
927 B
3
Indexable
Never
use std::sync::mpsc::{channel, Sender};
use std::thread::JoinHandle;

struct SingleThreadExec<T: FnOnce()->() + Send + 'static>{
    thread: JoinHandle<()>,
    sender: Sender<T>
}

impl<T: FnOnce()->() + Send + 'static> SingleThreadExec<T> {
    fn new() -> Self {
        let (sender, receiver) = channel();
        let thread = std::thread::spawn(move || {
            loop{
                let f: T = receiver.recv().unwrap();
                f();
            }
        });

        return SingleThreadExec {
            thread,
            sender
        }
    }

    fn submit(&self, task: T) {
        self.sender.send(task);
    }
/*
    fn close(self) {
        std::mem::drop(self.sender);
    }
 */
}

fn main() {
    let str = SingleThreadExec::new();
    str.submit(|| {println!("Funziona")});
    str.thread.join().unwrap();
    //str.submit(|| {println!("Funziona2")});
}