Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement LIFO for multiprocessing.Queue in python?

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?

like image 829
shijuza Avatar asked Nov 13 '15 11:11

shijuza


People also ask

How is LIFO implemented in Python?

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.

How does Python implement multiprocessing?

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.

What is LIFO in Python?

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.

How does Python multiprocessing queue work?

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.


1 Answers

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()
like image 120
Dunes Avatar answered Oct 16 '22 05:10

Dunes