Python等待队列和事件 [英] Python waiting for a queue and an event

查看:149
本文介绍了Python等待队列和事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个队列和一个事件.当事件设置为True时,我想退出循环,但是循环中有一个queue.get()阻塞,直到其中有东西为止.

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.

设置closeEvent事件标志后,如何终止self._commandQueue.get()的等待?

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

注意:我想避免依赖于队列的阻塞性质,而是希望基于队列的条件和eventflag进行阻塞

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()

推荐答案

您将需要Windows WaitForMultipleObjects()调用之类的功能,但是python事件和队列API不提供此类功能(但您可以使用win32api来实现)如果您确实是Windows,请使用此选项),因此,如果您确实需要同时检查两个事件源,答案是您不能不进行轮询(或猴子修补Event类以允许它)".

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)'.

但是,如果您更灵活一些,可以通过重新定义命令队列来安排类似的内容.如果命令队列是PriorityQueue,则一旦事件发出信号,您就可以将具有正常优先级的常规作业排队,并让一个额外的进程将具有更高优先级的'STOP'令牌排队.

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))

现在,您可以在自己的线程中运行wait_for_stop_signal,并且具有所需的行为(但是浪费一个线程而不是轮询,请选择对您的用例不利的事情).

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).

这篇关于Python等待队列和事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆