Source

nsocket / nsocket / core / engine / epoll.py

Full commit
from nsocket.core.engine import base

try:
    from select import epoll, EPOLLIN, EPOLLOUT, EPOLLET
except:
    from select26 import epoll, EPOLLIN, EPOLLOUT, EPOLLET

class Engine(base.AbstractEngine):

    def __init__(self):
        super(Engine, self).__init__()
        self._epoll = None

    def event_init(self):
        if not self._epoll:
            self._epoll = epoll()
    
    def add_reader(self, fd, cb):
        self.event_init()
        if fd not in self._reads:
            self._reads[fd] = cb
            self.selectable[fd] = fd
            self._epoll.register(fd, EPOLLIN|EPOLLET)
    
    def add_writer(self, fd, cb):
        self.event_init()
        if fd not in self._writes:
            self._writes[fd] = cb
            self.selectable[fd] = fd
            self._epoll.register(fd, EPOLLOUT|EPOLLET)

    def remove_reader(self, fd):
        if fd in self._reads:
            del self._reads[fd]
            if fd not in self._writes:
                del self.selectable[fd]
            self._epoll.unregister(fd)
#            print("remove reader %s" % fd)

    def remove_writer(self, fd):
        if fd in self._writes:
            del self._writes[fd]
            if fd not in self._reads:
                del self.selectable[fd]
            self._epoll.unregister(fd)
#            print("remove writer %s" % fd)

    def wait_event(self, timeout=60):
        epoll = self._epoll;
        max_event = len(self.selectable.values())
        #print("waiting.... %d %s" % (max_event,self.selectable))
        events = epoll.poll(timeout, max_event)
        return events
    
    def do_read_event(self, event):
        fd ,ev = event
        if ev & EPOLLIN:
            reads = self._reads
            if fd in reads:
                reads[fd](fd)

    def do_write_event(self, event):
        fd, ev = event
        if ev & EPOLLOUT:
            writes = self._writes
            if fd in writes:
                writes[fd](fd)