当前位置:   article > 正文

Python多进程使用Queue后卡死问题解决方案_python 多进程 queue 卡住

python 多进程 queue 卡住

很多人在使用Python的多进程过程,会用的进程的Queue来完成进程间的数据安全传递,因为Queue是进程内安全的,读写过程不用自己单独加锁和解锁,但是有一种情况就是Queue的在多进程里如果一直添加,会导致进程卡死,join永不退出进程,无限执行模式,具体Queue.put()的调度到多少个,没有做实验,但是1000内以内的可以忽略下面的讲解,因为只有数量够大才会将进程卡死,比如下面的代码 执行的效果就是

  1. from multiprocessing import Queue,Process
  2. def func(n,output_queue):
  3. start = time.time()
  4. print(n, time.time())
  5. count=0
  6. for i in range(10000000) :
  7. output_queue.put(i)
  8. count+= i
  9. stop = time.time()
  10. print(n, stop-start)
  11. if __name__ == '__main__':
  12. start = time.time()
  13. output = Queue()
  14. thread_list = []
  15. for i in range(10):
  16. th = Process(target=func, args=(i,output))
  17. thread_list.append(th)
  18. th.start()
  19. for th_item in thread_list:
  20. th_item.join()
  21. print("主进程执行完毕!")

执行结果:只有启动的时间戳,没有结束后的时间差打印

  1. 1 1623144548.5340202
  2. 2 1623144548.54046
  3. 0 1623144548.541418
  4. 4 1623144548.554847
  5. 5 1623144548.5567539
  6. 3 1623144548.569429
  7. 6 1623144548.588167
  8. 7 1623144548.588607
  9. 8 1623144548.599915
  10. 9 1623144548.604539

个人因为需要用多进程,也遇到了上面的问题,网上也搜索了很多,其实都给出明确的解决方法,大多是给出了问题,没有解答

1.卡死原因分析: 通过多次实验得出的结果推测,不是多进程执行有bug,是我们没理解多进程下的大数据执行的生产消费模式,比如子进程里 queue put进去,而主进程没有去消费,那么join是不会等到结束的

2.解决方案:加入消费模式,在join前,把队列的内容消费掉

 

  1. from multiprocessing import Queue,Process
  2. def func(n,output_queue):
  3. start = time.time()
  4. print(n, time.time())
  5. count=0
  6. for i in range(10000) :
  7. output_queue.put(i)
  8. count+= i
  9. stop = time.time()
  10. print(n, stop-start)
  11. if __name__ == '__main__':
  12. start = time.time()
  13. output = Queue()
  14. thread_list = []
  15. for i in range(10):
  16. th = Process(target=func, args=(i,output))
  17. thread_list.append(th)
  18. th.start()
  19. for th_item in thread_list:
  20. while th_item.is_alive():
  21. while False == output.empty():
  22. output.get()
  23. for th_item in thread_list:
  24. th_item.join()
  25. print("主进程执行完毕!")

执行结果:可以看到进程完成了最终的时间差打印

  1. 0 1623145645.839355
  2. 2 1623145645.840235
  3. 3 1623145645.8440099
  4. 1 1623145645.8445828
  5. 5 1623145645.8514628
  6. 6 1623145645.872386
  7. 4 1623145645.876878
  8. 7 1623145645.885157
  9. 8 1623145645.898742
  10. 9 1623145645.914007
  11. 3 0.8899681568145752
  12. 0 1.0251119136810303
  13. 2 1.0923209190368652
  14. 1 1.2704861164093018
  15. 5 1.3352081775665283
  16. 4 1.52469801902771
  17. 6 1.5615859031677246
  18. 7 1.6239848136901855
  19. 8 1.6524741649627686
  20. 9 1.6379320621490479
  21. 主进程执行完毕!

没有具体分析多进程内部代码,详细原因猜测,应该是queue的put 达到一个数量之后会锁住子进程,即时消费掉,才能保证子进程的持续执行

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/189715?site
推荐阅读
相关标签
  

闽ICP备14008679号