qsize() method of the Queue class

The qsize() method returns the approximate number of elements present the Queue instance. The example Python program adds elements into a Queue instance, through the parent thread and a child thread. Elements are removed using a child thread. The qsize() is called in the beginning and end of the get()/put() call combinations.

Queue Class Updated 23 Nov 2019 1 min read

Method Name

qsize

Method Signature

qsize()

Parameters

None

Return Value

Approximate number of elements present in a queue.Queue instance.

Method Overview

  • The method qsize() returns the number of elements present in a queue.Queue instance.

Note

  • If the qsize() returns > 0, it is not guaranteed that the next call to the get() method will not block or will not succeed.
  • If the qsize() returns < Queue.maxsize, it is not guaranteed that the next call to the put() method will not block or will not succeed.

Example

python
# Example Python program that uses Queue.qsize() method to get the approximate number of elements present in a queue.Queue instance

import queue

import threading

import time

# Thread function

def removeMessages(messagequeue):

    for i in range(4):

        time.sleep(1);

        messagequeue.get(time.time());

    print("Message remover exiting");

# Thread function

def generateMessages(messagequeue):

    for i in range(5):

        time.sleep(1);

        messagequeue.put(time.time());

    print("Message generator exiting");

# Create a queue with a maximum capacity of 7

packets = queue.Queue(maxsize=7);

print("Current size of the Queue");

print(packets.qsize());

# Create a thread that populates the queue

messageGenerator = threading.Thread(target=generateMessages, args=(packets,));

messageRemover = threading.Thread(target=removeMessages, args=(packets,));

messageGenerator.start();

messageRemover.start();

# Try adding upto maximum capacity from the

for i in range(2):

    time.sleep(1);

    packets.put(time.time(), block=False);

messageGenerator.join();

messageRemover.join();

print("Current size of the Queue");

print(packets.qsize());

print("Parent thread exiting");

Output

Output
Current size of the Queue

0

Message remover exiting

Message generator exiting

Current size of the Queue

3

Parent thread exiting