我有两个多处理线程,一个向队列添加项目,另一个需要遍历当前队列。我该如何进行迭代?或者,如何将当前队列转换为列表以进行迭代?
一些伪代码:
import multiprocessing as mp
thequeue = mp.Queue()
def func1():
global thequeue
while True:
item = readstream()
if item not None:
thequeue.put(item)
def func2():
while True:
for item in thequeue: # This only works for Lists, how to do this for queues?
if item == "hi":
print(item)
main():
mp.Process(target=func1).start()
mp.Process(target=func2).start()
Run Code Online (Sandbox Code Playgroud)
如果要根据for循环编写代码,可以使用以下两个参数形式iter:
def func2():
for item in iter(thequeue.get, None):
# do what you want
Run Code Online (Sandbox Code Playgroud)
并停止这个过程中,你只需要放None成thequeue,也可以使自己的信号停止,如果None你的情况是常见的。
请注意,与普通for循环不同,这将从队列中删除项目,就像get手动调用一样。在不删除项目的情况下,无法遍历进程间队列。
multiprocessing.Queue不直接支持迭代,因为for循环容器预计不会修改容器。这种非破坏性迭代在实现中是不可能支持的,而且设计时multiprocessing.Queue对于用例来说根本上是不合适的操作。multiprocessing.Queue
消费者应该使用get,它从队列中检索和删除项目:
def func2():
while True:
item = thequeue.get()
if item == 'hi':
print(item)
Run Code Online (Sandbox Code Playgroud)
如果您更喜欢循环的代码结构for,您可以使用两个参数,iter如 Sraw 的答案所示,但您仍然可以通过这种方式从队列中删除项目。multiprocessing.Queue在不删除项目的情况下不可能迭代 a 。