在python中引发异步事件

2024-09-27 07:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建类结构,在流中由事件生成控制。为此,我做了以下工作:

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}$

但是,我的问题是,基本上所有这些事件都是函数调用,过了一会儿,我就构建了一个庞大的递归调用堆栈。如何在通知事件的同时退出函数,或者在后台线程上继续运行现有函数。在


Tags: inifdef事件argselseclsfunc
1条回答
网友
1楼 · 发布于 2024-09-27 07:32:18

你可以:

  • 使用ThreadPools。与进程池相同的接口,但从multiprocessing.pool导入,如from multiprocessing.pool import ThreadPool。在

    您可以将事件名称和参数发送到池中供线程处理。如果队列已满,这可能会阻塞。

  • 在数据库中创建一个简单的事件队列(django模型),并使用单独的进程/线程来处理事件。这不会阻塞,因为您通常可以向数据库添加新对象。

  • 签出像celery这样的库,这些库为您提供了可伸缩性,并使在队列之上构建整个事件调度器成为可能。

ThreadPool示例:

from collections import defaultdict
from multiprocessing.pool import ThreadPool


class MyEvent:
    handlers = defaultdict(list)
    _pool = ThreadPool(5)

    @classmethod
    def setup(cls, notificationname, functionname):
        cls.handlers[notificationname].append(functionname)

    @classmethod
    def runonnotification(cls, notificationname, *args):
        thisfunclist = cls.handlers[notificationname]
        for func in thisfunclist:
            cls._pool.apply_async(func, args=args)


class SimpleExample(object):
    def __init__(self, a=1, b=2):
        SimpleExample.a = a
        SimpleExample.b = b
        MyEvent.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 = updateval
        if 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 ', data

    def negation(self):
        print 'negation enter'
        self.a = -self.a

    def handlemultipleupdates(self, a, b):
        print 'wow'
        self.a = a
        self.b = b

s = SimpleExample()
for x in [-50, 0, 1, 50, 70, 101]:
    s.updation(x)

MyEvent._pool.close()
MyEvent._pool.join()

相关问题 更多 >

    热门问题