处理来自高速通道的消息asynchronous预订,非阻塞

我有一个python“设备”运行在docker集装箱。 它连接到交叉开关路由器,在订阅的频道上接收高速公路/ WAMP事件消息。

当某个事件发布时,我的设备正在调用几秒钟内完成的方法。 现在,我希望它可以跳过或处理收到的同一事件的任何消息,而该方法仍在运行。 我试图通过使用Twisted的@inlinecallback修饰器并在设备上设置“self.busy”标志来实现此目的。

但是它不是立即返回,而是像正常的阻塞方法那样工作,以便传入的消息被一个接一个地处理。

这是我的代码:

from autobahn.twisted.wamp import ApplicationSession from twisted.internet.defer import inlineCallbacks class Pixel(ApplicationSession): @inlineCallbacks def onJoin(self, details): yield self.subscribe(self.handler_no_access, 'com.event.no_access') @inlineCallbacks def handler_no_access(self, direction): entries = len(self.handlers['no_access'][direction]) if entries == 0: self.handlers['no_access'][direction].append(direction) result = yield self._handler_no_access() return result else: yield print('handler_no_access: entries not 0: ', self.handlers['no_access']) @inlineCallbacks def _handler_no_access(self): for direction in self.handlers['no_access']: for message in self.handlers['no_access'][direction]: yield self._timed_switch(self.direction_leds[direction], 'red', 0.2, 5) self.handlers['no_access'][direction] = [] 

顺便说一下,我已经用self.handler字典带走了这个黑客之路。

编辑

阻塞方法是:

 yield self._timed_switch(self.direction_leds[direction], 'red', 0.2, 5) 

它控制RaspberryPi的GPIO上的Neopixel,使其闪烁1秒。 任何进一步的调用方法

 def handler_no_access(self, direction) 

而_timed_switch还没有完成,应该跳过,所以他们不堆积。

 @inlineCallbacks def handler_no_access(self, direction): direction = str(direction) if self.busy[direction] is False: self.busy[direction] = True # non-blocking now yield deferToThread(self._handler_no_access, direction) else: yield print('handler_no_access: direction {} busy '.format(direction)) def _handler_no_access(self, direction): # this takes 1s to execute self._timed_switch(self.direction_leds[direction], 'red', 0.2, 5) self.busy[direction] = False 

inlineCallbacks不会将阻止代码转换为非阻止代码。 这只是一个使用Deferreds的替代API。 延期只是一种pipe理callback的方法。

你需要重写你的阻止代码是非阻塞的其他方式。 你实际上并没有说你的代码的哪一部分被阻塞,也没有被阻塞,所以很难build议你如何做到这一点。 将阻塞代码变为非阻塞的唯一两​​个通用工具是线程和进程。 所以,你可以在一个单独的线程或进程中运行该函数。 该函数可能会或可能不会在这样的执行环境中工作(再次,没有办法知道,而不知道到底是什么)。

    Interesting Posts