[Tutor] Threads

Kent Johnson kent37 at tds.net
Tue Nov 16 01:08:30 CET 2004


Terry Carroll wrote:
> I just thought of a hybrid solution; have a lock object that's required to 
> be held to reference both the Queue and the Shutdown flag.  Each thread 
> would do something like this:
> 
>  get_lock()
>  if shutdown_flag == 'y':
>     self.shutdown='y'
>     else:
>       request=Queue.get()
>       if request.type = "shutdown"
>           self.shutdown='y'
>           shutdown_flag='y'   # tell the others
>       else:
>          [normal processing]
>  release_lock()
>  if self.shutdown ='y':
>     [shutdown stuff]

I think it can be as simple as this:
while not stopevent.isSet():
     try:
         task = producerQueue.get(True, 0.1)
         # process task
     except Queue.Empty:
         pass

where stopevent is a Queue.Event and producerQueue is a Queue.Queue.

>>What happens if you just leave the consumer threads blocked on the empty 
>>queue? If you will need them again, or if the entire process is 
>>short-lived, this is a simple solution. Just mark the consumers as 
>>daemon threads so the app will exit while they are still alive.
> 
> 
> I won't need them again.  Can the app exit with the threads still blocked?  
> Will Python kill off all the threads then?

If the threads are marked as daemon threads (call 
thread.setDaemon(True)) then Python will exit even if the thread is 
still alive.

Kent


More information about the Tutor mailing list