The empty() method of queue class

The empty() method of queue class returns False if a queue instance holds one or more elements. It returns True otherwise. Since queue is synchronised and used in producer/consumer scenarios, the return value of the empty() method does not guarantee that a subsequent get() or put() will not block.

Queue Class Updated 24 Nov 2019 1 min read

Method Name

empty

Method Signature

empty()

Parameters

None

Return Value

Returns True, if a Queue instance has zero elements.

Returns False, if a Queue instance has one or more elements.

Overview

  • The empty() method checks whether a Queue instance has any elements in it.
  • It returns True if there are no elements in the queue. Returns False otherwise.
  • Since the Queue is a synchronized class (not reentrant) when used by multiple threads, even if the empty() returns True, there is no guarantee that a put() operation will block.
  • Similarly, it is not guaranteed that a get() will not block even after the empty() method returns False.

Example

python
# Example python program that uses the q.empty() function

# before it proceeds to remove an element from the queue

import queue

import threading

import time

# Function that is executed as the thread body of the consumer thread

def consume(q):

    while(q.empty() == False):

        q.get();

        print("In consume():Removed an element from the Queue");

# Create a synchronized queue

q = queue.Queue();

consumerThread = threading.Thread(target=consume, args=(q,));

print("Size of the queue:%d"%q.qsize());

q.put("A");

print("Size of the queue:%d"%q.qsize());

# Start the purge thread

consumerThread.start();

print("Size of the queue after the consumer thread starts:%d"%q.qsize());

q.put("B");

# Wait till the consumer thread exits

consumerThread.join();

print("Size of the queue as the producer(parent) thread and the consumer thread exit:%d"%q.qsize());

Output

Output
Size of the queue:0

Size of the queue:1

In consume():Removed an element from the Queue

Size of the queue after the consumer thread starts:0

Size of the queue as the producer(parent) thread and the consumer thread exit:1