解决multiprocessing.Queue()无限阻塞问题

问题#

使用multiprocessing.Process()创建并行任务需要跨进程收集返回值
很自然想到使用queue进行出入参捕获,发现程序在each.join()无法继续

解决#

开始以为是返回值数量过多导致queue被塞满,打断点并为发现相应问题。
深入研究发现使用multiprocessing.Queue()产生的queue存在一些问题,主要有两方面:

  • multiprocessing.Queue() is an object whereas multiprocessing.Manager().Queue() is an address (proxy) pointing to shared queue managed by the multiprocessing.Manager() object.
  • therefore you can't pass normal multiprocessing.Queue() objects to Pool methods, because it can't be pickled.

资料进一步指出使用multiprocessing.Queue()并存放数据可能在join期间存在deadlock风险。
因此使用实例化的multiprocessing.Manager().Queue()代替原有的multiprocessing.Queue()始终是更好的选择。

# tasks = multiprocessing.Queue(core_num)
# results = multiprocessing.Queue()

manager = mp.Manager()
tasks = manager.Queue(core_num)
results = manager.Queue()

与此同时,还需要在queue.get()添加保护防止少数retrieve卡死整个程序

# retrieve info in queue with protection
for i in range(length):
    try:
        t = queue_res.get(timeout=10)
        if t is not None:
            # collect valid result
            self.ex_list.append(t)
    except Exception as error:
        print("Timeout occurred: " + str(error))

参考#

Python multiprocessing.Queue vs multiprocessing.manager().Queue() - Stack Overflow
16.6. multiprocessing — Process-based “threading” interface — Python 2.7.18 documentation
python - Why does multiprocessing.Process.join() hang? - Stack Overflow
Python multiprocessing queue get() timeout despite full queue - Stack Overflow

posted @   azureology  阅读(2571)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
历史上的今天:
2020-06-30 Python多进程pool.map展示进度条方法
点击右上角即可分享
微信分享提示
主题色彩