Pythonマルチプロセッシングを試みたWindowsでRuntimeErrorが発生する 質問する

Pythonマルチプロセッシングを試みたWindowsでRuntimeErrorが発生する 質問する

Windows マシンでスレッドとマルチプロセッシングを使用して、初めての正式な Python プログラムを試しています。しかし、プロセスを起動できず、Python から次のメッセージが表示されます。問題は、メインモジュールでスレッドを起動していないことです。スレッドはクラス内の別のモジュールで処理されます。

編集: ちなみにこのコードはUbuntuでは問題なく動作します。Windowsではうまく動作しません。

RuntimeError: 
            Attempt to start a new process before the current process
            has finished its bootstrapping phase.
            This probably means that you are on Windows and you have
            forgotten to use the proper idiom in the main module:
                if __name__ == '__main__':
                    freeze_support()
                    ...
            The "freeze_support()" line can be omitted if the program
            is not going to be frozen to produce a Windows executable.

私の元のコードはかなり長いのですが、短縮版のコードではエラーを再現できました。コードは 2 つのファイルに分かれており、最初のファイルはメイン モジュールで、プロセス/スレッドを処理してメソッドを呼び出すモジュールをインポートする以外はほとんど何もしません。2 番目のモジュールには、コードの核心部分があります。


テストメイン.py:

import parallelTestModule

extractor = parallelTestModule.ParallelExtractor()
extractor.runInParallel(numProcesses=2, numThreads=4)

並列テストモジュール.py:

import multiprocessing
from multiprocessing import Process
import threading

class ThreadRunner(threading.Thread):
    """ This class represents a single instance of a running thread"""
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        print self.name,'\n'

class ProcessRunner:
    """ This class represents a single instance of a running process """
    def runp(self, pid, numThreads):
        mythreads = []
        for tid in range(numThreads):
            name = "Proc-"+str(pid)+"-Thread-"+str(tid)
            th = ThreadRunner(name)
            mythreads.append(th) 
        for i in mythreads:
            i.start()
        for i in mythreads:
            i.join()

class ParallelExtractor:    
    def runInParallel(self, numProcesses, numThreads):
        myprocs = []
        prunner = ProcessRunner()
        for pid in range(numProcesses):
            pr = Process(target=prunner.runp, args=(pid, numThreads)) 
            myprocs.append(pr) 
#        if __name__ == 'parallelTestModule':    #This didnt work
#        if __name__ == '__main__':              #This obviously doesnt work
#        multiprocessing.freeze_support()        #added after seeing error to no avail
        for i in myprocs:
            i.start()

        for i in myprocs:
            i.join()

ベストアンサー1

if __name__ == '__main__':Windows では、サブプロセスは起動時にメイン モジュールをインポート (つまり実行) します。サブプロセスが再帰的に作成されるのを避けるには、メイン モジュールにガードを挿入する必要があります。

変更testMain.py:

import parallelTestModule

if __name__ == '__main__':    
    extractor = parallelTestModule.ParallelExtractor()
    extractor.runInParallel(numProcesses=2, numThreads=4)

おすすめ記事