Python多线程使用队列 - 程序永远被阻塞

标签 python multithreading queue block

我不确定我的程序的哪一部分是错误的。它将在两个队列的 join() 调用处被阻塞。但是,如果我删除了 2 个 join 调用,则该程序根本无法运行。

    import threading
    import Queue

    queue = Queue.Queue()
    out_queue = Queue.Queue()

    fruits = ['apple', 'strawberry', 'banana', 'peach', 'rockmelon']

    class WorkerThread(threading.Thread):
        def __init__(self, queue, out_queue):
            threading.Thread.__init__(self)
            self.queue = queue
            self.out_queue = out_queue
        def run(self):
            print 'run'
            while not self.queue.empty():
                name = self.queue.get()
                self.out_queue.put(name)
                self.queue.task_done()

    def main():
        print 'start'
        for i in xrange(5):
            t = WorkerThread(queue, out_queue)
            t.setDaemon(True)
            t.start()
        #populate the queue
        for fruit in fruits:
            queue.put(fruit)
        queue.join()
        out_queue.join()
        while not out_queue.empty():
            print out_queue.get()
        print 'end'

    if __name__=='__main__':
        main()

提前致谢。

最佳答案

您正在调用 out_queue.join(),它会等待 out_queue.task_done() 被调用相同次数 out_queue.put( ) 已被调用。但是,您永远不会调用 out_queue.task_done()。解决此问题的最佳方法是从一开始就不要调用 out_queue.join()

编辑:此外,您在启动 WorkerThread 后正在填充队列。这意味着工作线程有可能在您有机会插入所有元素之前运行并完成。在启动工作线程之前插入它们将解决此问题。

关于Python多线程使用队列 - 程序永远被阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21297291/

相关文章:

java - 阻塞队列与信号量

java - Java中的静态方法和线程安全

c++ - 终止工作线程的正确方法

.net - 一次性清除azure服务总线队列

python - 如何制作电影(与 matlab 相关)?

python - multiprocessing.Pool.map() 删除子类 ndarray 的属性

c - 在 C 中使用双向链表的队列 - 当我使用大量操作时,程序被终止

c# - 为什么 Stack<T> 和 Queue<T> 没有 Capacity 属性而 List<T> 有?

python - 按下按钮关闭 Raspberry Pi Python

python - 你将如何在 python 中编写 @debuggable 装饰器?