Python 等待队列和事件

Har*_*Har 5 python multithreading multiprocessing python-2.7

我有一个队列和一个事件。当事件设置为 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()
Run Code Online (Sandbox Code Playgroud)

sch*_*enk 4

你需要像 WindowsWaitForMultipleObjects()调用这样的东西,但 python 事件和队列 API 不提供这样的野兽(但如果你是严格的 Windows,你可以使用 win32api 来使用它),所以如果你真的需要检查两个事件源同时,答案是“如果没有轮询(或者猴子修补事件类以允许它),你就不能”。

但是如果您更灵活一点,您可以通过稍微重新定义命令队列来安排类似的事情。如果命令队列是 a PriorityQueue,则一旦事件发出信号,您可以将正常作业以正常优先级排队,并让额外的进程队列具有更高优先级的“STOP”标记。

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))
Run Code Online (Sandbox Code Playgroud)

现在你在它自己的线程中运行wait_for_stop_signal,并且你有你想要的行为(但是浪费一个线程而不是轮询,选择对你的用例来说更糟糕的)。