1、問題背景
在Python中,我想創建一個由事件生成控制流程的類結構。為此,我做了以下工作:
class MyEvent: EventName_FunctionName = {}@classmethoddef setup(cls, notificationname, functionname):if notificationname in MyEvent.EventName_FunctionName.keys():MyEvent.EventName_FunctionName[notificationname].append(functionname)else:MyEvent.EventName_FunctionName[notificationname] = [functionname]@classmethod def runonnotification(cls, notificationname, *args):thisfunclist = MyEvent.EventName_FunctionName[notificationname]for func in thisfunclist:if len(args) > 0:func(*args)else:func()
然后,我以以下方式使用它:
from FirstEventClass import MyEvent
class simpleexample:def __init__(self,a = 1, b = 2):simpleexample.a = asimpleexample.b = bMyEvent.setup('greater than 100',self.printerror)MyEvent.setup('dont do negative',self.negation)MyEvent.setup('many values recieved',self.handlemultipleupdates)def updation(self,updateval):if updateval > 100:MyEvent.runonnotification('greater than 100',updateval)self.a = updatevalif updateval < 0:MyEvent.runonnotification('dont do negative')def multipleupdates(self, a, b):MyEvent.runonnotification('many values recieved', a , b)def printerror(self,data):print ' something has gone wrong' ,datadef negation(self):print 'negation enter'self.a = -self.adef handlemultipleupdates(self, a , b):print 'wow'self.a = aself.b = b
然而,我的問題是,基本上所有這些事件都是函數調用,在很短的時間內,我構建了一個巨大的遞歸調用堆棧。我該如何在通知事件的同時退出函數,或者讓現有函數在后臺線程上繼續運行?
2、解決方案
方法一:使用多線程
一種解決方法是使用多線程。我們可以創建一個新線程來運行函數,然后在主線程中等待線程完成。例如:
import threadingdef my_function(data):print(data)# Create a new thread
thread = threading.Thread(target=my_function, args=("Hello, world!",))# Start the thread
thread.start()# Wait for the thread to finish
thread.join()
方法二:使用異步編程
另一種解決方法是使用異步編程。異步編程允許我們編寫并發代碼,而無需使用多線程或多進程。在Python中,我們可以使用asyncio
庫進行異步編程。例如:
import asyncioasync def my_function(data):print(data)# Create an event loop
loop = asyncio.get_event_loop()# Create a task
task = asyncio.create_task(my_function("Hello, world!"))# Run the event loop
loop.run_until_complete(task)
方法三:使用協程
協程是一種輕量級的線程,它可以暫停和恢復執行。協程可以用于編寫異步代碼,而無需使用多線程或多進程。在Python中,我們可以使用async
和await
關鍵字來編寫協程。例如:
async def my_function(data):print(data)async def main():await my_function("Hello, world!")asyncio.run(main())
這三種方法都可以解決在Python中異步觸發事件的問題。我們可以根據自己的需要選擇合適的方法。