Python 多处理池映射和 imap

avi*_*str 5 pool cpu-usage multiprocessing python-3.5

我有一个可以运行multiprocessing的脚本pool.map。问题是并非所有进程都需要很长时间才能完成,因此某些进程会休眠,因为它们会等到所有进程完成(与此问题相同的问题)。有些文件在不到一秒的时间内完成,其他文件则需要几分钟(或几小时)。

如果我正确理解手册(和这篇文章)pool.imap ,则不会等待所有进程完成,如果完成一个进程,它会提供一个新文件来处理。当我尝试这样做时,脚本正在加速要处理的文件,小文件按预期处理,大文件(需要更多时间处理)直到最后才完成(在没有通知的情况下被杀死?)。这是正常行为pool.imap,还是我需要添加更多命令/参数?time.sleep(100)当我将部分添加else为测试时,它正在处理更大的文件,但其他进程会进入睡眠状态。有什么建议 ?谢谢

def process_file(infile):
    #read infile
    #compare things in infile
    #acquire Lock, save things in outfile, release Lock
    #delete infile

def main():
    #nprocesses = 8
    global filename
    pathlist = ['tmp0', 'tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9']
    for d in pathlist:
        os.chdir(d)      
        todolist = []
        for infile in os.listdir():  
            todolist.append(infile)
        try:   
            p = Pool(processes=nprocesses)
            p.imap(process_file, todolist)
        except KeyboardInterrupt:                
            print("Shutting processes down")
           # Optionally try to gracefully shut down the worker processes here.       
            p.close()
            p.terminate()
            p.join()
        except StopIteration:
            continue     
        else:
            time.sleep(100)
            os.chdir('..')
        p.close()
        p.join() 

if __name__ == '__main__':
    main()    
Run Code Online (Sandbox Code Playgroud)

小智 3

由于您已经将所有文件放入列表中,因此可以将它们直接放入队列中。然后,该队列与子进程共享,子进程从队列中获取文件名并执行其操作。无需执行两次(首先进入列表,然后通过 Pool.imap 腌制列表)。Pool.imap 正在做完全相同的事情,但您却不知道。

todolist = []
for infile in os.listdir():  
    todolist.append(infile)
Run Code Online (Sandbox Code Playgroud)

可以替换为:

todolist = Queue()
for infile in os.listdir():  
    todolist.put(infile)
Run Code Online (Sandbox Code Playgroud)

完整的解决方案将如下所示:

def process_file(inqueue):
    for infile in iter(inqueue.get, "STOP"):
        #do stuff until inqueue.get returns "STOP"
    #read infile
    #compare things in infile
    #acquire Lock, save things in outfile, release Lock
    #delete infile

def main():
    nprocesses = 8
    global filename
    pathlist = ['tmp0', 'tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9']
    for d in pathlist:
        os.chdir(d)      
        todolist = Queue()
        for infile in os.listdir():  
            todolist.put(infile)
        process = [Process(target=process_file,
                      args=(todolist) for x in range(nprocesses)]
        for p in process:
            #task the processes to stop when all files are handled
            #"STOP" is at the very end of queue
            todolist.put("STOP")
        for p in process:
            p.start()
        for p in process:
            p.join()    
if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)