Queue: Which form is better/more Pythonic?

Jeff Hinrichs jlh at cox.net
Sat Feb 22 19:27:52 CET 2003


"Alex Martelli" <aleax at aleax.it> wrote in message
news:fOO5a.217413$0v.6083352 at news1.tin.it...
> Jeff Hinrichs wrote:
>
> > Is it better to break out of an infinite loop when the queue is empty
> > while 1:
> >     try:
> >         msg=qMsg.get_nowait()
> >         ...do something with msg...
> >     except Queue.Empty:
> >         break
> >
> > or to loop against the .empty()
> >
> > while not qMsg.empty():
> >     try:
> >         msg=qMsg.get_nowait()
> >         ...do something with msg...
> >     except Queue.Empty:
> >         pass
> >
> > The docs say that .empty() is not reliable and I want to make sure that
I
> > pass all messages from the producer to a consumer. Although my limited
>
> The queue COULD be empty just because the producer isn't finished
> producing yet, and that's a risk you run with either approach (also,
> get_nowait used like this will produce a busy loop chewing up your
> CPU).  I suggest that you should rather have the producer post to
> the queue a special message conventionally meaning "OK, I'm done!"
> and that you break out of your "while 1:" loop when you meet it: this
> is FAR more reliable.  Also, use get, not get_nowait, for performance.
>
> > missing a non-empty queue.  Am I a worrying too much?
>
> No, just, I suspect, worrying about the wrong things.
Very probably as this is my first foray in to using threads in any language.
I am writing small "learning" apps to figure out what I  don't know and
fill those gaps, wrt the threading module.<g>

The loop that checks for messages in the queue is very tight in this
example,
but it would be run only periodically in the actual app.  Which is to be a
magnetic stripe card reading program, user swipes card through reader, data
comes in via serial port, handled by a threaded routine that passes the data
back to the display portion(main loop), which then formats the message,
displays it to the screen and then prints it out to a thermal printer.
producer -> transformer -> consumer.

Since the transformer/ui section will only be checking the loop periodically
and
I don't want to block on reading the queue since that would block the UI
loop.
After telling you this, am I still wrong on using get_nowait() ?

-Jeff






More information about the Python-list mailing list