mrning
V2EX  ›  Python

请教有关 Python 多进程 multiprocessing 中使用 Queue 产生的死锁问题

By mrning at 2021 年 3 月 26 日 · 3452 次点击

想实现多进程执行某项任务( moviepy 多进程),获得返回的值( frame,numpy 数组)。 尝试过用 ApplyResult.get() 获取,不过返回的内容不能被 pickle,所以用了 queue 。 或者还有其他更好的方法么

下面是个简单的 demo,似乎遇到了死锁,网上没有找到好的方案,求教

import multiprocessing as mp
from multiprocessing import Pool,Queue
import os,time,random
 
def worker(msg,q):
    t_start = time.time()
    print("%s  Started with pid: %d"%(msg,os.getpid()))
    a = 2**100000000
    t_stop = time.time()
    print(msg,"  Finishing with time: %0.2f"%(t_stop-t_start))    
    q.put(a)
    
 
if __name__ == '__main__':
    mp.set_start_method("spawn")
    pool = mp.Pool(3) 
    q=mp.Queue()
    for i in range(10):
        print(i)
        pool.apply_async(worker,(i,q,))
    pool.close()
    for thread_i in range(10):
            result = q.get()
            print(result)

    pool.join()
    print("Waiting")
8 条回复  •  2021-03-26 16:00:04 +08:00
xiaolinjia
   1
xiaolinjia  
   2021 年 3 月 26 日   ❤️ 1
q = mp.Manager().Queue()。个人经验是当你用 apply.async 卡住没抛出异常的时候,把他改成 apply 阻塞型,看是报啥错。
nikan999
   2
nikan999  
   2021 年 3 月 26 日   ❤️ 1
打印错误
Queue objects should only be shared between processes through inheritance
参考:
https://stackoverflow.com/questions/9908781/sharing-a-result-queue-among-several-processes
Jblue
   3
Jblue  
   2021 年 3 月 26 日
可以把返回值存起来放到 redis 之类的
mrning
   4
mrning  
OP
   2021 年 3 月 26 日
@xiaolinjia
@nikan999
改了下,在 linux 下执行,能看到 print 的信息了。worker 函数执行完了,然后在 result = q.get()这里卡住了


@Jblue
实在不行的话...也是个办法 😊
mrning
   5
mrning  
OP
   2021 年 3 月 26 日
![py11.PNG]( https://i.loli.net/2021/03/26/qp5MS1olWGixHmA.png)

代码及执行结果
nikan999
   6
nikan999  
   2021 年 3 月 26 日
print 2**100000000
这个数太大了导致卡在打印这一块
mrning
   7
mrning  
OP
   2021 年 3 月 26 日
@nikan999 原来如此👍

/(ㄒoㄒ)/~~
hareandlion
   8
hareandlion  
   2021 年 3 月 26 日 via Android
queue 用 mp.Manager().Queue(),输出超级大数让我机器内存无法释放……
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 38ms · 3.9.8.5