4

I have an inter-process queue that is usually empty and only once in a while does something appear in it. In one of my threads I want to define a while loop like this:

def mythread(queue1):

    while (queue1.get_nowait() != 1):
        #do stuff

This works great until the queue is empty which happens quickly in my case. When the queue is empty calling get_nowait() or get(False) raises the empty queue exception. Is there any way to check the queue without blocking AND without raising the empty exception?

willpower2727
  • 769
  • 2
  • 8
  • 23
  • If you don't want to block, then something has to happen when you call it on an empty queue. Catch the exception and handle it. – mata Aug 26 '16 at 16:29

1 Answers1

8

use empty method

if queue1.empty():
   pass
else:
   # get items from the queue

Note: doc says "not reliable" (no kidding).

I suppose that's because it can return True (queue is empty) while a message is posted, so the operation is not as atomic as catching the exception. Well, followed by a get_nowait() call I suppose it doesn't matter unless some other thread can consume the queue as well, in which case a racing condition could occur and the queue could be empty when you try to read from it!

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219