基于不同操作系统提供的多路IO通知机制,实现了一个可以针对文件描述符或者同类结构进行事件监听开发的小型框架,基于tornado的IOLoop实现。主要结构如下:
LoopImpl类依据不同操作系统,按照epoll的接口实现了统一的loop注册方式:
class LoopImpl(object): """ Base class for concrete implementations of event loop class """ def __init__(self): pass def close(self): raise NotImplementedError() def register(self, fd, event_type): raise NotImplementedError() def unregister(self, fd): raise NotImplementedError() def modify(self, fd): raise NotImplementedError() def pool(self, timeout): """ Pool the ready event """ raise NotImplementedError()据此分别实现了三种不同的方式:
class EpollLoop(LoopImpl) class KQueueLoop(LoopImpl) class SelectLoop(LoopImpl) Loop类提供统一的静态方法返回唯一实例,选取LoopImpl方式时依据当前系统支持的最优方式进行,优先选择epoll,其次为kqueue,select方式作为最终的补充。
...... if hasattr(select, 'epoll'): self._impl = EpollLoop() model = 'epoll' elif hasattr(select, 'kqueue'): self._impl = KQueueLoop() model = 'kqueue' elif hasattr(select, 'select'): self._impl = SelectLoop() model = 'select' else: raise Exception('can not find any async event stratege') ......每个Loop实例维护三类不同的handler列表,分别为
- poll handler:发生某个事件后调用
- pure handler:无条件调用
- periodic handler:按照一定时间间隔周期性调用
每个handler都有一个 _LoopHandler 类的对象相对应。每一类handler都可以动态添加(add接口)和删除(remove接口)。最终Loop类使用start接口开始整个handler的处理循环。
详细代码见github: https://github.com/OshynSong/eventloop