基於不同操作系統提供的多路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