在Python中,你可以使用多线程或多进程来实现函数的并行处理。这里有两种方法:
concurrent.futures
库中的ThreadPoolExecutor
实现多线程并行处理:import concurrent.futures
import time
def func(x):
print(f"Processing {x}")
time.sleep(1)
return x * x
data = [1, 2, 3, 4, 5]
with concurrent.futures.ThreadPoolExecutor() as executor:
results = list(executor.map(func, data))
print("Results:", results)
concurrent.futures
库中的ProcessPoolExecutor
实现多进程并行处理:import concurrent.futures
import time
def func(x):
print(f"Processing {x}")
time.sleep(1)
return x * x
data = [1, 2, 3, 4, 5]
with concurrent.futures.ProcessPoolExecutor() as executor:
results = list(executor.map(func, data))
print("Results:", results)
注意:多线程并行处理在I/O密集型任务中效果较好,而多进程并行处理在计算密集型任务中效果较好。在选择并行处理方法时,请根据实际需求和任务类型进行选择。