【问题标题】:python multiprocessing script does not exitpython多处理脚本不退出
【发布时间】:2016-12-22 13:45:56
【问题描述】:

我正在尝试让 python2.7 多处理模块更加舒适。因此,我编写了一个小脚本,将文件名和所需的进程数作为输入,然后启动多个进程以将函数应用于队列中的每个文件名。它看起来像这样:

import multiprocessing, argparse, sys
from argparse import RawTextHelpFormatter

def parse_arguments():
    descr='%r\n\nTest different functions of multiprocessing module\n%r' % ('_'*80, '_'*80)
    parser=argparse.ArgumentParser(description=descr.replace("'", ""), formatter_class=RawTextHelpFormatter)
    parser.add_argument('-f', '--files', help='list of filenames', required=True, nargs='+')
    parser.add_argument('-p', '--processes', help='number of processes for script', default=1, type=int)
    args=parser.parse_args()
    return args 

def print_names(name):
    print name


###MAIN###

if __name__=='__main__':
    args=parse_arguments()
    q=multiprocessing.Queue()
    procs=args.processes
    proc_num=0
    for name in args.files:
        q.put(name)
    while q.qsize()!=0:
        for x in xrange(procs):
            proc_num+=1
            file_name=q.get()
            print 'Starting process %d' % proc_num
            p=multiprocessing.Process(target=print_names, args=(file_name,))
            p.start()
            p.join()
            print 'Process %d finished' % proc_num

脚本工作正常,每次旧进程完成时都会启动一个新进程(我认为这就是它的工作原理?),直到队列中的所有对象都用完。但是,脚本在完成队列后不会退出,而是处于空闲状态,我必须使用Ctrl+C 将其杀死。这里有什么问题?

感谢您的回答!

【问题讨论】:

  • 你为什么使用队列?子进程之间不共享,不妨遍历args.files。
  • 以前我使用“multiprocessing.Pool()”遍历文件列表以生成多个进程。但是,对于大文件列表,进程的数量最终会减少,因为(这就是我认为发生的情况)当文件较小时,某些进程会更快地完成任务列表。在这里,我尝试使用队列在每次进程完成时使用新文件启动新进程,以优化程序的速度。

标签: python queue multiprocessing exit multiple-processes


【解决方案1】:

好像你在上面混了一些东西。 您生成一个进程,让它完成它的工作,并等待它退出,然后在下一次迭代中开始一个新进程。使用这种方法,您会陷入顺序处理,这里没有实际执行多处理。

也许你想以此为起点:

import sys
import os
import time
import multiprocessing as mp

def work_work(q):
    # Draw work from the queue
    item = q.get()
    while item:
        # Print own process id and the item drawn from the queue
        print(os.getpid(), item)
        # Sleep is only for demonstration here. Usually, you 
        # do not want to use this! In this case, it gives the processes
        # the chance to "work" in parallel, otherwise one process
        # would have finished the entire queue before a second one
        # could be spawned, because this work is quickly done.
        time.sleep(0.1)
        # Draw new work
        item = q.get()

if __name__=='__main__':
    nproc = 2  # Number of processes to be used
    procs = [] # List to keep track of all processes

    work = [chr(i + 65) for i in range(5)]
    q = mp.Queue() # Create a queue...
    for w in work:
        q.put(w) # ...and fill it with some work.

    for _ in range(nproc):
        # Spawn new processes and pass each of them a reference
        # to the queue where they can pull their work from.
        procs.append(mp.Process(target=work_work, args=(q,)))
        # Start the process just created.
        procs[-1].start()

    for p in procs:
        # Wait for all processes to finish their work. They only
        # exit once the queue is empty.
        p.join()

【讨论】:

  • 好的,我看到了如何将流程放在一个列表中并在所有完成后完成它们确实是我想做的。小问题:当一个进程完成队列中的一个项目但队列仍然满时,它会选择另一个,以便我继续使用相同数量的进程运行我的程序,直到队列为空?
  • 是的,这正是这里将要发生的事情。
  • 嘿,实际上我检查了你的代码,问题仍然存在。进程执行并清空队列,但没有完成,而是进入睡眠状态,脚本停在那里......
  • 这是因为work_work函数中的具体实现:while item:一旦队列为空就中断。如果item 是None,则替换为while True: 并添加time.sleep(100)。
猜你喜欢
  • 2017-01-08
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 2014-12-03
  • 2019-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多