Is there a way to protect a piece of critical code?

Paul Rubin http
Thu Jan 11 01:25:44 EST 2007


"Hendrik van Rooyen" <mail at microcorp.co.za> writes:
> am aware of Queue module - the same app uses it for something else.
> I dont like too many try -- excepts in the code - I find they confuse
> me when I try to read it later - and in this case I cannot block on waiting for
> the queue to fill.

Do you have multiple threads reading from the same queue?  If not then
you can use queue.empty() to see whether the queue is empty.  If yes,
queue.empty isn't reliable (it can return nonempty, and then another
thread empties out the queue before you get a chance to read it).  But
you could always wrap the queue:

    QUEUE_IS_EMPTY = object()   # global sentinel

    def get_from_queue(queue):
       try:
          return queue.get(block=False)
       except Queue.Empty:
          return QUEUE_IS_EMPTY

Maybe it's worth adding a method like that to the Queue module in the stdlib.



More information about the Python-list mailing list