gpt4 book ai didi

等待队列和事件的 Python

转载 作者:太空狗 更新时间:2023-10-30 02:04:03 29 4
gpt4 key购买 nike

我有一个队列和一个事件。我想在事件设置为 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 来使用它),所以如果你真的需要同时检查两个事件源,答案是“你不能不进行轮询(或者猴子修补 Event 类以允许它)”。

但是如果你更灵活一点,你可以通过稍微重新定义你的命令队列来安排类似的东西。如果命令队列是 PriorityQueue,您可以使用正常优先级对正常作业进行排队,并在事件发出信号后让额外的进程对具有更高优先级的“STOP” token 进行排队。

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,并且您拥有了您想要的行为(但是浪费了一个线程而不是轮询,选择对您的用例来说更糟糕的)。

关于等待队列和事件的 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25116935/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com