Free cookie consent management tool by TermsFeed qsize() method of the Queue class | Pythontic.com

Qsize() method of the Queue class

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:

# 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:

Current size of the Queue

0

Message remover exiting

Message generator exiting

Current size of the Queue

3

Parent thread exiting


Copyright 2025 © pythontic.com