我有一个队列和一个事件。我想在事件设置为 True 时退出循环,但是循环中有一个queue.get(),它会阻塞,直到其中有东西为止。
当设置 closeEvent 事件标志时,如何中止 self._commandQueue.get() 的等待?
注意:我想避免依赖于队列的阻塞性质,并希望根据队列的条件和事件标志进行阻塞
def _execute(self):
while not self._closeEvent.isSet():
nextCommand = self._commandQueue.get()
self._commandExecutor.execute(nextCommand)
self._commandQueue.task_done()
你需要像Windows这样的东西WaitForMultipleObjects()
调用,但 python 事件和队列 API 不提供这样的野兽(但如果你是严格的 Windows,你可以使用 win32api 来使用它),所以如果你真的需要并行检查两个事件源,答案是'如果没有轮询(或者猴子修补事件类以允许它),你就不能”。
但如果你更灵活一点,你可以通过稍微重新定义你的命令队列来安排类似的事情。如果命令队列是PriorityQueue
,一旦事件发出信号,您可以将正常作业以正常优先级排队,并让额外的进程以更高优先级排队“停止”令牌。
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))
现在你跑wait_for_stop_signal
在它自己的线程中,并且您有您想要的行为(但浪费一个线程而不是轮询,选择对您的用例来说更糟糕的)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)