这是我用来测试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
。
有人看到我在这里做错了吗?
答案 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()