How to run functions in parallel?

后端 未结 6 1140
我在风中等你
我在风中等你 2020-11-22 10:32

I researched first and couldn\'t find an answer to my question. I am trying to run multiple functions in parallel in Python.

I have something like this:



        
6条回答
  •  生来不讨喜
    2020-11-22 10:53

    If your functions are mainly doing I/O work (and less CPU work) and you have Python 3.2+, you can use a ThreadPoolExecutor:

    from concurrent.futures import ThreadPoolExecutor
    
    def run_io_tasks_in_parallel(tasks):
        with ThreadPoolExecutor() as executor:
            running_tasks = [executor.submit(task) for task in tasks]
            for running_task in running_tasks:
                running_task.result()
    
    run_io_tasks_in_parallel([
        lambda: print('IO task 1 running!'),
        lambda: print('IO task 2 running!'),
    ])
    

    If your functions are mainly doing CPU work (and less I/O work) and you have Python 2.6+, you can use the multiprocessing module:

    from multiprocessing import Process
    
    def run_cpu_tasks_in_parallel(tasks):
        running_tasks = [Process(target=task) for task in tasks]
        for running_task in running_tasks:
            running_task.start()
        for running_task in running_tasks:
            running_task.join()
    
    run_cpu_tasks_in_parallel([
        lambda: print('CPU task 1 running!'),
        lambda: print('CPU task 2 running!'),
    ])
    

提交回复
热议问题