I understand the difference between a queue and stack. But if I spawn multiple processes and send messages between them put in multiprocessing.Queue
how do I access the latest element put in the queue first?
For a LIFO (Last in First out Queue), the element that is entered last will be the first to come out. An item in a queue is added using the put(item) method. To remove an item, get() method is used.
In this example, at first we import the Process class then initiate Process object with the display() function. Then process is started with start() method and then complete the process with the join() method. We can also pass arguments to the function using args keyword.
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.
The multiprocessing. Queue provides a first-in, first-out FIFO queue, which means that the items are retrieved from the queue in the order they were added. The first items added to the queue will be the first items retrieved.
You can use a multiprocessing manager to wrap a queue.LifoQueue
to do what you want.
from multiprocessing import Process
from multiprocessing.managers import BaseManager
from time import sleep
from queue import LifoQueue
def run(lifo):
"""Wait for three messages and print them out"""
num_msgs = 0
while num_msgs < 3:
# get next message or wait until one is available
s = lifo.get()
print(s)
num_msgs += 1
# create manager that knows how to create and manage LifoQueues
class MyManager(BaseManager):
pass
MyManager.register('LifoQueue', LifoQueue)
if __name__ == "__main__":
manager = MyManager()
manager.start()
lifo = manager.LifoQueue()
lifo.put("first")
lifo.put("second")
# expected order is "second", "first", "third"
p = Process(target=run, args=[lifo])
p.start()
# wait for lifoqueue to be emptied
sleep(0.25)
lifo.put("third")
p.join()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With