我了解队列和堆栈之间的区别。但是如果我生成多个进程并在它们之间发送消息multiprocessing.Queue
如何访问首先放入队列中的最新元素?
您可以使用多处理管理器 https://docs.python.org/3/library/multiprocessing.html#multiprocessing-managers包裹一个queue.LifoQueue https://docs.python.org/3/library/queue.html#queue.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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)