詳解Python實現(xiàn)多進程異步事件驅(qū)動引擎
更新時間:2017年08月25日 14:11:16 作者:JimmyLaw
本篇文章主要介紹了詳解Python實現(xiàn)多進程異步事件驅(qū)動引擎,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本文介紹了詳解Python實現(xiàn)多進程異步事件驅(qū)動引擎,分享給大家,具體如下:
多進程異步事件驅(qū)動邏輯

邏輯
code
# -*- coding: utf-8 -*-
'''
author: Jimmy
contact: 234390130@qq.com
file: eventEngine.py
time: 2017/8/25 上午10:06
description: 多進程異步事件驅(qū)動引擎
'''
__author__ = 'Jimmy'
from multiprocessing import Process, Queue
class EventEngine(object):
# 初始化事件事件驅(qū)動引擎
def __init__(self):
#保存事件列表
self.__eventQueue = Queue()
#引擎開關
self.__active = False
#事件處理字典{'event1': [handler1,handler2] , 'event2':[handler3, ...,handler4]}
self.__handlers = {}
#保存事件處理進程池
self.__processPool = []
#事件引擎主進程
self.__mainProcess = Process(target=self.__run)
#執(zhí)行事件循環(huán)
def __run(self):
while self.__active:
#事件隊列非空
if not self.__eventQueue.empty():
#獲取隊列中的事件 超時1秒
event = self.__eventQueue.get(block=True ,timeout=1)
#執(zhí)行事件
self.__process(event)
else:
# print('無任何事件')
pass
#執(zhí)行事件
def __process(self, event):
if event.type in self.__handlers:
for handler in self.__handlers[event.type]:
#開一個進程去異步處理
p = Process(target=handler, args=(event, ))
#保存到進程池
self.__processPool.append(p)
p.start()
#開啟事件引擎
def start(self):
self.__active = True
self.__mainProcess.start()
#暫停事件引擎
def stop(self):
"""停止"""
# 將事件管理器設為停止
self.__active = False
# 等待事件處理進程退出
for p in self.__processPool:
p.join()
self.__mainProcess.join()
#終止事件引擎
def terminate(self):
self.__active = False
#終止所有事件處理進程
for p in self.__processPool:
p.terminate()
self.__mainProcess.join()
#注冊事件
def register(self, type, handler):
"""注冊事件處理函數(shù)監(jiān)聽"""
# 嘗試獲取該事件類型對應的處理函數(shù)列表,若無則創(chuàng)建
try:
handlerList = self.__handlers[type]
except KeyError:
handlerList = []
self.__handlers[type] = handlerList
# 若要注冊的處理器不在該事件的處理器列表中,則注冊該事件
if handler not in handlerList:
handlerList.append(handler)
def unregister(self, type, handler):
"""注銷事件處理函數(shù)監(jiān)聽"""
# 嘗試獲取該事件類型對應的處理函數(shù)列表,若無則忽略該次注銷請求
try:
handlerList = self.__handlers[type]
# 如果該函數(shù)存在于列表中,則移除
if handler in handlerList:
handlerList.remove(handler)
# 如果函數(shù)列表為空,則從引擎中移除該事件類型
if not handlerList:
del self.__handlers[type]
except KeyError:
pass
def sendEvent(self, event):
#發(fā)送事件 像隊列里存入事件
self.__eventQueue.put(event)
class Event(object):
#事件對象
def __init__(self, type =None):
self.type = type
self.dict = {}
#測試
if __name__ == '__main__':
import time
EVENT_ARTICAL = "Event_Artical"
# 事件源 公眾號
class PublicAccounts:
def __init__(self, eventManager):
self.__eventManager = eventManager
def writeNewArtical(self):
# 事件對象,寫了新文章
event = Event(EVENT_ARTICAL)
event.dict["artical"] = u'如何寫出更優(yōu)雅的代碼\n'
# 發(fā)送事件
self.__eventManager.sendEvent(event)
print(u'公眾號發(fā)送新文章\n')
# 監(jiān)聽器 訂閱者
class ListenerTypeOne:
def __init__(self, username):
self.__username = username
# 監(jiān)聽器的處理函數(shù) 讀文章
def ReadArtical(self, event):
print(u'%s 收到新文章' % self.__username)
print(u'%s 正在閱讀新文章內(nèi)容:%s' % (self.__username, event.dict["artical"]))
class ListenerTypeTwo:
def __init__(self, username):
self.__username = username
# 監(jiān)聽器的處理函數(shù) 讀文章
def ReadArtical(self, event):
print(u'%s 收到新文章 睡3秒再看' % self.__username)
time.sleep(3)
print(u'%s 正在閱讀新文章內(nèi)容:%s' % (self.__username, event.dict["artical"]))
def test():
listner1 = ListenerTypeOne("thinkroom") # 訂閱者1
listner2 = ListenerTypeTwo("steve") # 訂閱者2
ee = EventEngine()
# 綁定事件和監(jiān)聽器響應函數(shù)(新文章)
ee.register(EVENT_ARTICAL, listner1.ReadArtical)
ee.register(EVENT_ARTICAL, listner2.ReadArtical)
for i in range(0, 20):
listner3 = ListenerTypeOne("Jimmy") # 訂閱者X
ee.register(EVENT_ARTICAL, listner3.ReadArtical)
ee.start()
#發(fā)送事件
publicAcc = PublicAccounts(ee)
publicAcc.writeNewArtical()
test()
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
利用python實現(xiàn)平穩(wěn)時間序列的建模方式
這篇文章主要介紹了利用python實現(xiàn)平穩(wěn)時間序列的建模方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
深入理解Pytorch微調(diào)torchvision模型
PyTorch是一個基于Torch的Python開源機器學習庫,用于自然語言處理等應用程序。它主要由Facebookd的人工智能小組開發(fā),不僅能夠 實現(xiàn)強大的GPU加速,同時還支持動態(tài)神經(jīng)網(wǎng)絡,這一點是現(xiàn)在很多主流框架如TensorFlow都不支持的2021-11-11
Python獲取二維數(shù)組的行列數(shù)的2種方法
這篇文章主要介紹了Python獲取二維數(shù)組的行列數(shù)的2種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-02-02
Python計算一個點到所有點的歐式距離實現(xiàn)方法
今天小編就為大家分享一篇Python計算一個點到所有點的歐式距離實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Python開發(fā)游戲之井字游戲的實戰(zhàn)步驟
最近正在學習Python,所以最近做了一個關于Python的實例,下面這篇文章主要給大家介紹了關于Python開發(fā)游戲之井字游戲的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-02-02

