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