【问题标题】:How do I notify queue.join() in python to stop blocking even if the current queue contains unprocessed elements?即使当前队列包含未处理的元素,如何在 python 中通知 queue.join() 停止阻塞?
【发布时间】:2025-11-29 12:30:01
【问题描述】:

我有一个主线程阻塞等待优先队列(PQ)中的项目由消费者线程处理。消费者线程从不同的填充线程接收项目。每当消费者线程收到高优先级的“TERMINATOR”项目时,它就会死亡。但是由于主线程正在等待队列元素被处理,所以它永远不会退出。有没有办法让我通知 PQ.join() 返回而不使用 while 循环来清空我的队列(如果我使用 while 循环,队列中的大量项目会导致很多延迟)

【问题讨论】:

    标签: python multithreading queue priority-queue blocking


    【解决方案1】:

    您可以等待消费者线程而不是优先级队列,这似乎是您想要等待的东西,即consumer_thread.join() 而不是PQ.join()

    【讨论】:

    • 是的,谢谢这解决了我的问题。但另一方面,我不明白为什么我的 PQ.join() 没有解除阻塞,即使在遇到终结器对象时我使 PQ.unfinished_tasks = 0 也是如此。
    • 来自文档:Queue.task_done() Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue. 链接:docs.python.org/3/library/queue.html
    • 这意味着设置PQ.unfinished_tasks = 0 不会触发join() 继续,只会调用task_done() 的次数与您放入项目的次数相同。
    最近更新 更多