Simple question about Queue.Queue and threads

Steven Steven.Rumbalski at
Mon Feb 8 15:51:02 CET 2010

On Feb 5, 7:45 am, "Frank Millman" <fr... at> wrote:
> Hi all
> Assume you have a server process running, a pool of worker threads to
> perform tasks, and aQueue.Queue() to pass the tasks to the workers.
> In order to shut down the server cleanly, you want to ensure that the
> workers have all finished their tasks. I like the technique of putting a
> None onto thequeue, and have each worker check for None, put None back onto
> thequeue, and terminate itself.
> The main program would look something like this -
>     q.put(None)
>     for worker in worker_threads:
>         worker.join()
> At this point you can be sure that each thread has completed its tasks and
> terminated itself.
> However, thequeueis not empty - it still has the final None in it.
> Is it advisable to finalise the cleanup like this? -
>     while not q.empty():
>         q.get()
>         q.task_done()
>     q.join()
> Or is this completely redundant?
> Thanks
> Frank Millman

Queue objects have support for this signaling baked in with
q.task_done and q.join.

After the server process has put all tasks into the queue, it can join
the queue itself, not the worker threads.


This will block until all tasks have been gotten AND completed.  The
worker threads would simply do this:
task_data = q.get()

Using pairs of get and task_done you no longer need to send a signal.
Just exit the server process and the worker threads will die (assuming
of course, you set .setDaemon(True) before starting each worker

Steven Rumbalski

More information about the Python-list mailing list