0

This is a script I'm using to test the Queue module:

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()

It works and creates two threads, printing each fruits item once, however fruit_queue.join() never seems to be continued as the end message Finished! is never printed:

$ 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

At first I wasn't sure and added global fruit_queue in to the worker() function, but it gave me SyntaxError: name 'fruit_queue' is local and global when I ran it.

Does anyone see anything that I'm doing wrong here?

user1447941
  • 3,675
  • 10
  • 29
  • 34

1 Answers1

0

Try that:

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()
swietyy
  • 786
  • 1
  • 9
  • 15
  • It would be better to pass it in the args option, e.g. `Thread(target=worker, args=(fruit_queue,))`. – Eryk Sun Oct 19 '12 at 16:04