Overview
- The Queue class in the queue module from the Python Standard Library provides a queue that can be shared between multiple threads.
- E.g., Producer thread(s) and consumer thread(s) sharing a Queue instance to accomplish a work – also known as work crew as the group of threads work to complete a task picking up work packets from the common Queue instance. In a simple producer/consumer scenario - two work crews are involved. A producer crew and a consumer crew.
- The synchronization is provided by the Queue itself.
- The Queue class does not provide reentrancy.
Example
# Example Python program that uses a common Queue in a producer/consumer model
import queue
import threading
import time
# Create a producer thread
def messageMaker(mq):
for i in range(5):
if i == 4:
mq.put(None);
print("Added message: %d"%i);
else:
mq.put("Message:%s"%time.time(), block=False);
print("Added message: %d"%i);
print("Message maker exiting");
# Create a consumer thread
def messageReader(mq):
while(True):
msg = mq.get();
print("Read:%s"%msg);
if msg is None:
break;
print("Message reader exiting");
# Create a shared queue for the use of producer and consumer threads
mq = queue.Queue(maxsize = 5);
# Create producer and consumer threads
makerThread = threading.Thread(target=messageMaker, args=(mq,));
readerThread = threading.Thread(target=messageReader, args=(mq,));
# Start the threads
makerThread.start();
readerThread.start();
# With for the threads to complete
makerThread.join();
readerThread.join();
print("Parent thread exiting");Output
Added message: 0
Added message: 1
Read:Message:1574449719.224082
Added message: 2
Read:Message:1574449719.224226
Added message: 3
Read:Message:1574449719.224352
Added message: 4
Read:Message:1574449719.2244961
Message maker exiting
Read:None
Message reader exiting
Parent thread exiting