Python threads and queue example
Threads do not exit normally in this code (they are indeed blocked when the queue is empty). The program doesn't wait for them because they're daemon threads.
The program doesn't exit immediately and doesn't block forever because of q.join
and q.task_done
calls.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done()
to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join()
unblocks, and the program exists without waiting for daemon threads.
nacholibre
Updated on March 02, 2020Comments
-
nacholibre about 4 years
I'm new to python (I come from PHP), I've been reading tutorials and trying things for a couple of days but I can't understand this queue example (http://docs.python.org/2/library/queue.html)
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.daemon = True t.start() for item in source(): q.put(item) q.join() # block until all tasks are done
The thing I don't understand is how the worker thread completes and exists. I've read q.get() blocks until an item is available, so if all items are processed and none is left in the queue why q.get() doesn't block forever?
-
me_and over 9 yearsThat solution is rather risky. If the worker threads are quick, they'll test
q.empty()
before any items have been added to the queue, and then exit before they've done anything. Equally, if there's a single item left in the queue and two threads testq.empty()
simultaneously, they'll both continue but one will get an item off the queue while the other will block atq.get()
.