Queue() question. This post is pretty long.

grocery_stocker cdalten at gmail.com
Thu Apr 16 19:02:54 CEST 2009


I don't get how   item = self.__queue.get() gets advanced to

if item is None:

in the following code.

>>> import time
>>> from threading import Thread
>>> import Queue
>>>
>>> WORKER = 2
>>>
>>> class Worker(Thread):
...     def __init__(self, queue):
...         Thread.__init__(self)
...         self.__queue = queue
...     def run(self):
...         while 1:
...           item = self.__queue.get()
...           if item is None:
...              break
...           print "task", item, "finished"
...

>>> for i in range(WORKER):
...     Worker(queue).start()
...
>>> for i in range(10):
...     queue.put(i)
...
>>> task 0 finished
task 1 finished
task 2 finished
task 3 finished
task 4 finished
task 5 finished
task 6 finished
task 7 finished
task 8 finished
task 9 finished
>>> for i in range(WORKER):
...     queue.put(None)
...

This because when I do something like

[cdalten at localhost ~]$ python
Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
[GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Queue
>>> queue = Queue.Queue()
>>>
>>> while 1:
...    item = queue.get()
...    if item == 'done':
...       break
...
this
is
a
test
done

[3]+  Stopped                 python
[cdalten at localhost ~]$ kill %3

It appears that only item = queue.get() called. Ie, the block never
advances to if item == 'done':
like in the first example




More information about the Python-list mailing list