Skip to main content
 首页 » 编程设计

python之遍历多处理队列

2025年05月04日21dudu

我有两个多处理线程,一个向队列添加项目,另一个需要遍历当前队列。我如何进行迭代?或者,如何将当前队列转换为列表以进行迭代?

一些伪代码:

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() 

请您参考如下方法:

如果您想根据for 循环编写代码,您可以使用two-argument form of iter。 :

def func2(): 
    for item in iter(thequeue.get, None): 
        # do what you want 

要停止这个过程,你只需要将一个None放入thequeue,或者如果None你可以自己发出停止信号> 在你的情况下很常见。

请注意,与普通的 for 循环不同,这将从队列中删除项目,就像手动调用 get 一样。在不删除项目的情况下,无法遍历进程间队列。