我想创建类结构,在流中由事件生成控制。为此,我做了以下工作:
class MyEvent:
EventName_FunctionName = {}
@classmethod
def 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()
然后按以下方式使用:
^{pr2}$但是,我的问题是,基本上所有这些事件都是函数调用,过了一会儿,我就构建了一个庞大的递归调用堆栈。如何在通知事件的同时退出函数,或者在后台线程上继续运行现有函数。在
你可以:
使用ThreadPools。与进程池相同的接口,但从
multiprocessing.pool
导入,如from multiprocessing.pool import ThreadPool
。在您可以将事件名称和参数发送到池中供线程处理。如果队列已满,这可能会阻塞。
在数据库中创建一个简单的事件队列(django模型),并使用单独的进程/线程来处理事件。这不会阻塞,因为您通常可以向数据库添加新对象。
签出像celery这样的库,这些库为您提供了可伸缩性,并使在队列之上构建整个事件调度器成为可能。
ThreadPool
示例:相关问题 更多 >
编程相关推荐