Run separate processes in parallel - Python

前端 未结 1 2044
耶瑟儿~
耶瑟儿~ 2021-02-04 13:44

I use the python \'multiprocessing\' module to run single processes on multiple cores but I want to run a couple of independent processes in parallel.

For example, Proces

相关标签:
1条回答
  • 2021-02-04 14:14

    From 16.6.1.5. Using a pool of workers:

    from multiprocessing import Pool
    
    def f(x):
        return x*x
    
    if __name__ == '__main__':
        pool = Pool(processes=4)              # start 4 worker processes
        result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
        print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
        print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"
    

    You can, therefore, apply_async against a pool and get your results after everything is ready.

    from multiprocessing import Pool
    
    # all your methods declarations above go here
    # (...)
    
    def main():
        pool = Pool(processes=3)
        parsed = pool.apply_async(Process1, [largefile])
        pattern = pool.apply_async(Process2, [bigfile])
        calc_res = pool.apply_async(Process3, [integer])
    
        pool.close()
        pool.join()
    
        final = FinalProcess(parsed.get(), pattern.get(), calc_res.get())
    
    # your __main__ handler goes here
    # (...)
    
    0 讨论(0)
提交回复
热议问题