0

这是我用来测试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当我运行它时它给了我。

有没有人看到我在这里做错了什么?

4

1 回答 1

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()
于 2012-10-19T14:34:59.903 回答