use of Queue
Diez B. Roggisch
deets at nospam.web.de
Wed Aug 27 05:56:29 EDT 2008
Alexandru Mosoi wrote:
> how is Queue intended to be used? I found the following code in python
> manual, but I don't understand how to stop consumers after all items
> have been produced. I tried different approaches but all of them
> seemed incorrect (race, deadlock or duplicating queue functionality)
>
>
> def worker():
> while True:
> item = q.get()
> do_work(item)
> q.task_done()
>
> q = Queue()
> for i in range(num_worker_threads):
> t = Thread(target=worker)
> t.setDaemon(True)
> t.start()
>
> for item in source():
> q.put(item)
>
> q.join() # block until all tasks are done
Put a sentinel into the queue that gets interpreted as "terminate" for the
workers. You need of course to put it in there once for each worker.
Diez
More information about the Python-list
mailing list