我了解队列和堆栈之间的区别。但是,如果我生成多个进程并在它们之间发送消息,multiprocessing.Queue
我如何首先访问队列中的最新元素?
问问题
2927 次
3 回答
7
您可以使用多处理管理器来包装 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()
于 2015-11-13T13:52:56.047 回答
-2
如果只关心最新的值或对象,设置 maxsize = 1
import multiprocessing as mp
lifo = mp.Queue(maxsize=1)
于 2021-05-02T04:00:11.193 回答
-5
multiprocessing.Queue
不是数据类型。它是在两个进程之间进行通信的一种手段。它不能与Stack
这就是为什么没有 API 可以将最后一项从队列中弹出。
我认为您的想法是使某些消息比其他消息具有更高的优先级。当它们被发送到侦听进程时,您希望尽快将它们出列,绕过队列中的现有消息。
您实际上可以通过创建两个来实现此效果multiprocessing.Queue
:一个用于普通数据有效负载,另一个用于优先消息。那你就不用担心了getting the last item
。只需将两种不同类型的消息隔离到两个队列中。
于 2015-11-13T11:28:46.270 回答