任务完成后,队列无法完成

时间:2012-10-19 14:11:26

标签: python multithreading task-queue

这是我用来测试Queue模块的脚本:

from Queue import Queue
from threading import Thread

def worker(fruit_queue):

    while True:
        fruit = fruit_queue.get()
        print 'A fruit: ' + fruit
        fruit_queue.task_done()


def main():

    fruits = ['apple', 'orange', 'kiwi', 'banana', 'plum',
              'grape', 'mango', 'cherry', 'lime', 'lemon']

    fruit_queue = Queue()

    print 'Printing fruits...'

    for fruit in fruits:
        fruit_queue.put(fruit)

    for i in range(2):
        t = Thread(target=worker(fruit_queue))
        t.daemon = True
        t.start()

    fruit_queue.join()
    print 'Finished!'


if __name__ == '__main__':
    main()

它工作并创建两个线程,打印每个fruits项一次,但fruit_queue.join()似乎永远不会继续,因为永远不会打印结束消息Finished!

$ python fruit.py
Printing fruits...
A fruit: apple
A fruit: orange
A fruit: kiwi
A fruit: banana
A fruit: plum
A fruit: grape
A fruit: mango
A fruit: cherry
A fruit: lime
A fruit: lemon

起初我不确定并将global fruit_queue添加到worker()函数中,但是当我运行它时它给了我SyntaxError: name 'fruit_queue' is local and global

有人看到我在这里做错了吗?

1 个答案:

答案 0 :(得分:0)

试试:

from Queue import Queue
from threading import Thread

def worker():
    while True:
        fruit = fruit_queue.get()
        print 'A fruit: ' + fruit
        fruit_queue.task_done()

def main():
    fruits = ['apple', 'orange', 'kiwi', 'banana', 'plum',
              'grape', 'mango', 'cherry', 'lime', 'lemon']

    print 'Printing fruits...'

    for i in range(2):
        t = Thread(target=worker)
        t.daemon = True
        t.start()

    for fruit in fruits:
        fruit_queue.put(fruit)

    fruit_queue.join()
    print 'Finished!'

if __name__ == '__main__':
    fruit_queue = Queue()   
    main()