1

私は、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。ここで何が問題なのですか?

回答ありがとうございます。

4

1 に答える 1

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()
于 2016-12-22T14:03:23.147 に答える