我有两个多处理线程,一个线程将项目添加到队列,另一个线程需要遍历当前队列。我该如何进行迭代?或者,如何将当前队列转换为要迭代的列表?
一些伪代码:
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()
答案 0 :(得分:2)
通过for
循环获得的那种迭代对于线程间或进程间通信队列根本上是不合适的操作,这就是multiprocessing.Queue
不支持它的原因。相反,消费者应使用get
从队列中删除项目:
def func2():
while True:
item = thequeue.get()
if item == 'hi':
print(item)
答案 1 :(得分:1)
您甚至不需要while True
循环。
def func2():
for item in iter(thequeue.get, None):
# do what you want
要停止此过程,只需将None
放入thequeue
。
如果您遇到的情况是None
,也可以发出自己的信号来停止。