python - python 条件变量忙等待吗?

标签 python concurrency

我有一个多线程程序,其中主线程会在任意时间点将事件放入队列中,并且我只希望在队列不为空时运行后台线程。也就是说,我不希望我的线程忙等待,我希望它进入休眠状态并仅在收到通知时才唤醒。我的类中有一个名为 queueNotEmpty 的条件变量,只要有东西添加到队列中,主线程就会调用 notify() 。以下内容是否满足我的需求,或者仍然在 wait() 调用中忙于等待?

while(not self.terminate):
    try:
        eventName, info = self.eventQueue.get(block=False)
        event = trigger(eventName, info)
    except Queue.Empty:
        self.queueNotEmpty.acquire()
        self.queueNotEmpty.wait()
        self.queueNotEmpty.release()

最佳答案

您正试图踢开一扇敞开的门。这基本上与上面的代码执行相同的操作,代码中没有额外的复杂性,并且没有由于潜在的竞争条件而浪费的循环周期。

while(not self.terminate):
    eventName, info = self.eventQueue.get()
    event = trigger(eventName, info)

队列阻塞不是主动等待。

更新:Queue 的内部工作原理在博客文章 "Python threads synchronization: Locks, RLocks, Semaphores, Conditions, Events and Queues" 中进行了描述。 。根据该消息来源,它是这样实现的:

def get(self, block=True, timeout=None):
    ...
    self.not_empty.acquire()
    try:
        ...
        elif timeout is None:
            while not self._qsize():
                self.not_empty.wait()
        item = self._get()
        self.not_full.notify()
        return item
    finally:
        self.not_empty.release()

关于python - python 条件变量忙等待吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22098216/

相关文章:

python - 如何使用异步理解?

python - Pandas :仅从日期时间列中提取日历年

python - Django 1.8 到 1.9 升级 : django. core.exceptions.AppRegistryNotReady: Apps aren't loaded yet

python - 如何使用pywinauto模拟游戏中的按键

Python multiprocessing.Queue 放置和获取死锁

c# - 当当前任务阻塞时,如何在 .NET 中安排另一项任务?

c++ - 为什么 sleep() 会阻塞 std::ostream

python - gcc 编译器无法识别 -fno-plt 选项

java - 我可以在 Oracle 中进行原子 MERGE 吗?

java - 当其他线程可以访问它时从数据库更新静态映射