python使用ThreadPoolExecutor、ProcessPoolExecutor进行任务并行

在Python中,可以使用concurrent.futures.ThreadPoolExecutor来实现多线程调用函数。

from concurrent.futures import ThreadPoolExecutor

def my_function(arg1, arg2):
    print(f"Processing {arg1} and {arg2}")

with ThreadPoolExecutor(max_workers=3) as executor:
    for i in range(5):
        executor.submit(my_function, i, i*2)

需要获取返回值,可通过future.result()获取


from concurrent.futures import ThreadPoolExecutor
import time

def calculate_square(number):
    time.sleep(1)  # 模拟耗时操作
    return number * number

with ThreadPoolExecutor(max_workers=3) as executor:
    # 提交任务并保存future对象
    future1 = executor.submit(calculate_square, 2)
    future2 = executor.submit(calculate_square, 3)
    future3 = executor.submit(calculate_square, 4)
    
    # 获取结果(会阻塞直到任务完成)
    print(f"2的平方: {future1.result()}")
    print(f"3的平方: {future2.result()}")
    print(f"4的平方: {future3.result()}")

使用多少线程数合理?对于cpu计算密集型,可以使用cpu核心数作为线程数。对于I/O密集型,可以使用核心数x2。使用如下代码可以获得核心数

import os
cpu_count = os.cpu_count()  # 返回逻辑核心数(含超线程)‌
print(f"CPU核心数: {cpu_count}")

但是对于cpu密集型的任务,更推荐使用多进程的ProcessPoolExecutor,接口和ThreadPoolExecutor一样。但是要说明的是,开启进程、进程间通信和销毁进程要比同样的线程步骤耗时更大,如果要执行的任务不是明显的cpu密集型,那么使用ProcessPoolExecutor并不一定要快于ThreadPoolExecutor