【问题标题】:Script using multiprocessing module does not terminate使用多处理模块的脚本不会终止
【发布时间】:2014-12-31 13:11:53
【问题描述】:

以下代码不打印"here"。问题是什么? 我在我的两台机器(Windows 7、Ubuntu 12.10)和 http://www.compileonline.com/execute_python_online.php 它不会在所有情况下都打印"here"

from multiprocessing import Queue, Process


def runLang(que):
    print "start"
    myDict=dict()
    for i in xrange(10000):
        myDict[i]=i
    que.put(myDict)
    print "finish"


def run(fileToAnalyze):
    que=Queue()
    processList=[]
    dicList=[]
    langs= ["chi","eng"]
    for lang in langs:
        p=Process(target=runLang,args=(que,))
        processList.append(p)
        p.start()

    for p1 in processList:
        p1.join()

    print "here"

    for _ in xrange(len(langs)):
        item=que.get()
        print item
        dicList.append(item)

if __name__=="__main__":
    processList = []
    for fileToAnalyse in ["abc.txt","def.txt"]:
        p=Process(target=run,args=(fileToAnalyse,))
        processList.append(p)
        p.start()
    for p1 in processList:
        p1.join()

【问题讨论】:

    标签: python python-2.7 multiprocessing python-multiprocessing


    【解决方案1】:

    这是因为当您将put 大量项目放入multiprocessing.Queue 时,一旦底层Pipe 已满,它们最终会在内存中缓冲。在从Queue 的另一端开始读取之前,缓冲区不会被刷新,这将允许Pipe 接受更多数据。在其所有Queue 实例的缓冲区完全刷新到其底层Pipe 之前,Process 无法终止。这意味着如果您尝试join 一个进程而没有另一个进程/线程在其Queue 上调用get,您可能会死锁。这是mentioned in the docs

    警告

    如上所述,如果子进程已将项目放入队列(并且 它没有使用JoinableQueue.cancel_join_thread),那么那个过程 直到所有缓冲的项目都被刷新到 管道。

    这意味着如果您尝试加入该进程,您可能会遇到死锁 除非您确定所有已放入队列的项目 已被消耗。同样,如果子进程是非守护进程 那么当父进程试图加入它的所有进程时,它可能会在退出时挂起 非恶魔的孩子。

    请注意,使用管理器创建的队列不存在此问题。

    您可以通过在清空父项中的 Queue 之前不调用 join 来解决此问题:

    for _ in xrange(len(langs)):
        item = que.get()
        print(item)
        dicList.append(item)
    
    # join after emptying the queue.
    for p in processList:
        p.join()
    
    print("here")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-22
      • 2011-06-11
      • 2012-11-17
      • 2015-05-08
      • 2012-10-28
      • 1970-01-01
      • 2021-05-09
      相关资源
      最近更新 更多