How to spawn parallel child processes on a multi-processor system?

前端 未结 4 1765
北海茫月
北海茫月 2020-12-04 06:52

I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this sec

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 07:30

    What you are looking for is the process pool class in multiprocessing.

    import multiprocessing
    import subprocess
    
    def work(cmd):
        return subprocess.call(cmd, shell=False)
    
    if __name__ == '__main__':
        count = multiprocessing.cpu_count()
        pool = multiprocessing.Pool(processes=count)
        print pool.map(work, ['ls'] * count)
    

    And here is a calculation example to make it easier to understand. The following will divide 10000 tasks on N processes where N is the cpu count. Note that I'm passing None as the number of processes. This will cause the Pool class to use cpu_count for the number of processes (reference)

    import multiprocessing
    import subprocess
    
    def calculate(value):
        return value * 10
    
    if __name__ == '__main__':
        pool = multiprocessing.Pool(None)
        tasks = range(10000)
        results = []
        r = pool.map_async(calculate, tasks, callback=results.append)
        r.wait() # Wait on the results
        print results
    

提交回复
热议问题