March 2003
Intermediate to advanced
656 pages
39h 30m
English
qsize
q.qsize( )Returns the number of items that are currently in
q.
Queue
offers a good example of the idiom
“it’s easier to ask forgiveness
than permission” (EAFP), covered in Chapter 6. Due to multithreading, each non-mutating
method of q can only be advisory. When
some other thread executes and mutates q,
things can change between the instant a thread gets the information
and the very next moment, when the thread acts on the information.
Relying on the “look before you
leap” (LBYL) idiom is futile, and fiddling with
locks to try and fix things is a substantial waste of effort. Just
avoid LBYL code such as:
ifq.empty( ): print "no work to perform" else:x=q.get_nowait( )
and instead use the simpler and more robust EAFP approach:
try:x=q.get_nowait( ) except Queue.Empty: print "no work to perform"