Method Name
get
Method Signature
get([block[, timeout]])
Return Value
NoneType
Parameters
| block | - A Boolean value specifying whether get() should block till an object is available in the Queue. |
| - The default value of this parameter is True. - If True, it waits for an object to arrive at the empty Queue by some process. - If True while the timeout parameter is specified, then get() blocks for only the number of timeout seconds. - If False, it returns immediately upon encountering an empty Queue, raising a queue.Empty exception. | |
| timeout | This parameter tells how many seconds to wait, while trying to read from an empty Queue. If the get is not successful till the expiry of timeout seconds, an exception queue.Empty is raised. |
Method Overview
- The method get() reads and removes a Python object from a Queue instance.
- Once an object is removed from the Queue using get() it is not available in the Queue.
- Through the parameters block and timeout how long the get() can wait before a successful read of an item from the Queue.
Example
import multiprocessing
import queue
import time
QUEUE_LIMIT = 6
# Function for consumer process
def consumerFunction(messageQueue):
count = 0
while count < QUEUE_LIMIT:
try:
count = count + 1
print("Consumer read:%s"%messageQueue.get(timeout=2))
except queue.Empty:
print("Consumer:Timeout reading from the Queue")
if __name__ == "__main__":
multiprocessing.set_start_method = "fork";
messageQueue = multiprocessing.Queue(maxsize=QUEUE_LIMIT)
consumerProcess = multiprocessing.Process(target=consumerFunction, args=(messageQueue,))
# Start the consumer (Consumer starts first...look at the timeout for get() in consumer function)
consumerProcess.start()
# Parent process acting as the producer of messages
for i in range(1, QUEUE_LIMIT+1):
messageQueue.put("Message%d"%i)
print("Producer added:Message%d"%i)
time.sleep(1)
# Wait for the consumer process to complete
consumerProcess.join()Output
Producer added:Message1
Consumer read:Message1
Producer added:Message2
Consumer read:Message2
Producer added:Message3
Consumer read:Message3
Producer added:Message4
Consumer read:Message4
Producer added:Message5
Consumer read:Message5
Producer added:Message6
Consumer read:Message6