1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use core_poll::CorePoll;
use std::net::TcpStream;
use std::thread::spawn;
use std::sync::mpsc::Sender;
use std::sync::mpsc::Receiver;
use std::sync::mpsc::channel;
use std::os::unix::io::AsRawFd;
use std;
use super::threadpool::ThreadPool;
use std::os::unix::io::FromRawFd;

pub enum Ctrl {
    ADD(i32),
    RM(i32),
    SHUTDOWN,
}
/// Executor to manage socket poll and execute response to handle message
pub struct Executor {
    ctrl_sender: Sender<Ctrl>,
}

impl Executor {
    pub fn new(maxconn: i32,
               handler: fn(fd: i32, socket: &mut TcpStream, commander: Sender<Ctrl>))
               -> Self {
        let (tx, rx): (Sender<Ctrl>, Receiver<Ctrl>) = channel();
        let tx_clone = tx.clone();
        let thpool = ThreadPool::new(4);
        spawn(move || {
            let mut epoll = CorePoll::new(maxconn);
            loop {
                match rx.try_recv() {
                    Ok(ctrl) => {
                        match ctrl {
                            Ctrl::ADD(fd) => {
                                epoll.add(fd);
                            }
                            Ctrl::RM(fd) => {
                                epoll.remove(fd);
                            }
                            Ctrl::SHUTDOWN => {
                                epoll.close();
                                // drop(epoll);
                                // return;
                            }
                        }
                    }
                    Err(_) => {}
                }

                let list = epoll.wait();

                for fd in list {
                    let cloned = tx_clone.clone();
                    thpool.execute(move || {
                        unsafe {
                            let mut stream: TcpStream = TcpStream::from_raw_fd(fd);
                            handler(fd, &mut stream, cloned);
                            std::mem::forget(stream);
                        }
                    });
                }
            }

        });

        Executor { ctrl_sender: tx }
    }
    /// Add socket to epoll list
    pub fn add(&self, sock: TcpStream) {
        self.ctrl_sender.send(Ctrl::ADD(sock.as_raw_fd())).unwrap();
        std::mem::forget(sock);
    }
}