如何在python中为multiprocessing.Queue实现LIFO?

shi*_*uza 9 python queue lifo python-multiprocessing

我了解队列和堆栈之间的区别。但是,如果我生成多个进程并在它们之间发送消息放入multiprocessing.Queue如何访问放入队列中的最新元素?

Dun*_*nes 6

您可以使用多处理管理器来包装 aqueue.LifoQueue以执行您想要的操作。

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()
Run Code Online (Sandbox Code Playgroud)


Ant*_*ong -6

multiprocessing.Queue不是一种数据类型。它是两个进程之间进行通信的一种手段。它无法与Stack

这就是为什么没有 API 可以将最后一项从队列中弹出的原因。

我认为您的想法是让某些消息比其他消息具有更高的优先级。当它们被发送到侦听进程时,您希望尽快将它们出队,绕过队列中的现有消息。

实际上,您可以通过创建两个来实现此效果multiprocessing.Queue:一个用于普通数据有效负载,另一个用于优先级消息。那么你就不需要担心了getting the last item。只需将两种不同类型的消息分离到两个队列中即可。