Why does Python Queue return an approximate size in qsize ()?

In doc qsize (), it says: return the approximate size of the queue.

Why can't he just return the exact size of this queue? I understand that a queue can be accessed by several threads, but at the moment I'm calling a function, I think that you can still return the exact size of this moment.

+7
source share
2 answers

Precisely because other threads are accessing it. By the time you try to use the size returned with qsize (), the queue may have changed. It would be better if the documentation had something like this:

Returns the size of the queue. Please note that in a multi-threaded environment, the size can change at any time, making it only an approximate value of the actual size.

+24
source

I agree that the “rough” is not the clearest choice of words, but, as Ned argues, they are trying to indicate that just because the queue size at time t1 was 7 does not mean that it will still be size 7, when you click or post values ​​later.

The problem is that as long as the size returned with qsize is still correct, when you go to pushing / popping a value from this queue, it may unexpectedly behave in a multi-threaded environment.

For example:

 q = Queue() if q.qsize > 0: # size is 1 here # another thread runs here and gets an item from your queue # this get fails and throws an exception in your thread: item = q.get(False) # do whatever processing with item you need to do 

This is an LBYL “Look in front of you” example, and it is dangerous due to the potential state of the race here when multiple threads are accessing the queue.

In this case, you must approve the EAFP or "apologize except for permission" and do the following:

 from Queue import Queue, Empty import time q = Queue() try: item = q.get(False) # do whatever processing with item you need to do except Empty: time.sleep(1) 
+5
source

All Articles