python等待事件后运行,Python等待队列和事件

I have a queue and an event. I would like to exit the loop when the event is set to True, however there is a queue.get() in the loop which blocks until there is something in it.

How can I abort the waiting of the self._commandQueue.get() when the closeEvent Event flag is set?

Note: I want to avoid depending on the blocking nature of the queue and want to block based on the condition of the queue and the eventflag

def _execute(self):

while not self._closeEvent.isSet():

nextCommand = self._commandQueue.get()

self._commandExecutor.execute(nextCommand)

self._commandQueue.task_done()

解决方案

You would need something like the Windows WaitForMultipleObjects() call, but the python event and queue API don't offer such a beast (but you could use win32api to use that if you are strictly windows), so if you really need BOTH event sources to be checked in parallel, the answer is 'you cannot without polling (or monkey patching the Event class to allow it)'.

But if you are a bit more flexible, you can arrange something like it, by redefining your command queue a bit. If the command queue is a PriorityQueue, you could queue your normal jobs with normal priority and have an extra process queue a 'STOP' token with higher priority, once your event signals.

STOP = None

def _execute(self):

while 1:

nextCommand = self._commandQueue.get()[1]

if nextCommand is STOP:

break

self._commandExecutor.execute(nextCommand)

self._commandQueue.task_done()

def wait_for_stop_signal(self):

self._closeEvent.wait()

self._commandQueue.put((-1, STOP))

Now you run wait_for_stop_signal in its own thread, and you have the behaviour you want (but waste one thread instead of polling, pick whats worse for your use case).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值