Pythonのconcurrent.futures
モジュールにはProcessPoolExecutor
というクラスがあります。このクラスを用いると、CPUに負荷がかかる計算処理などの並列実行が可能になります。
以下に、ProcessPoolExecutor
を用いた並列処理の一例を示します。
import time
from concurrent.futures import ProcessPoolExecutor
def f(args):
wait_seconds = args
time.sleep(wait_seconds)
try:
with open(f"{wait_seconds}.txt", "w") as file:
print(f"{wait_seconds}", file=file)
except FileNotFoundError as e:
pass
return wait_seconds
if __name__ == "__main__":
params = [(1), (7), (2), (3), (4), (5), (6)]
with ProcessPoolExecutor(max_workers=3) as executor:
[print(r) for r in executor.map(f, params, chunksize=3)]
このコードでは、ProcessPoolExecutor
のmap
メソッドを用いて並列処理を行っています。map
メソッドのchunksize=3
パラメータにより、params
が3つずつの集団に仕分けされ、各集団ごとに逐次処理が行われます。
このように、ProcessPoolExecutor
を用いることで、Pythonにおける並列処理を効率的に行うことが可能です。ただし、max_workers
やCPU、処理の内容と綿密にご相談することが重要です。