[Tutor] Threads

Terry Carroll carroll at tjc.com
Tue Nov 16 00:36:45 CET 2004


On Mon, 15 Nov 2004, Kent Johnson wrote:

> Terry Carroll wrote:
>  
> > I suppose I could [add] that "shutdown element" multiple times, once for 
> > each consumer thread spawned, but that seems so inelegant.
>
> Simple and effective, though, as long as you know how many consumers 
> there are.

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]

> 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?

> You might be interested in these recipes:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/196618

Thanks; they look interesting.  I'll take a closer look.



More information about the Tutor mailing list