这是我用来测试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
当我运行它时它给了我。
有没有人看到我在这里做错了什么?