调用正在忽略方法d

2024-05-12 20:36:09 发布

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

我正在使用PyDispatcherWrapt@synchronized装饰器。当PyDispatcher调用我的一个处理程序方法时,它忽略了函数decorator。你知道吗

我已经为此创建了一个测试用例。运行以下代码会同时运行两个线程,但预期的行为是@synchronized修饰符应阻止第二个线程进入_method_b方法,直到_method_a完成:

from wrapt.decorators import synchronized
import time
from twisted.internet import reactor, threads
from twisted.internet.defer import inlineCallbacks
from pydispatch import dispatcher

class TestSync(object):

    def __init__(self):
        dispatcher.connect(self._method_a, signal="A")
        dispatcher.connect(self._method_b, signal="B")

    @synchronized
    def _method_a(self):
        print "Before Sleep A"
        time.sleep(2)
        print "After Sleep A"

    @synchronized
    def _method_b(self):
        print "Before Sleep B"
        time.sleep(2)
        print "After Sleep B"

    def method_a(self):
        self._method_a()

    def method_b(self):
        self._method_b()

    def test(self):
        reactor.callInThread(dispatcher.send, signal="A")
        reactor.callInThread(dispatcher.send, signal="B")

ts = TestSync()
reactor.callLater(0, ts.test)
reactor.run()

但是,如果不是从Pydispatch调用方法,而是从另一个方法调用它们,@synchronized装饰器确实可以按预期工作。这可以通过使用method_amethod_b方法来测试,这两种方法依次调用修饰方法:

def __init__(self):
    dispatcher.connect(self.method_a, signal="A")
    dispatcher.connect(self.method_b, signal="B")

这是预期的行为吗?我怎样才能告诉你不要忽视装饰师呢?你知道吗


Tags: 方法fromimportselfsignaltimedefconnect