\

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)]

このコードでは、ProcessPoolExecutormapメソッドを用いて並列処理を行っています。mapメソッドのchunksize=3パラメータにより、paramsが3つずつの集団に仕分けされ、各集団ごとに逐次処理が行われます。

このように、ProcessPoolExecutorを用いることで、Pythonにおける並列処理を効率的に行うことが可能です。ただし、max_workersやCPU、処理の内容と綿密にご相談することが重要です。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です