LoginSignup
0
0

More than 1 year has passed since last update.

python で ProcessPoolExecutor を使ったマルチプロセスのサンプル

Posted at

はじめに

タイトルの通り。ProcessをThreadに変更するとマルチスレッドにできるので、使い勝手が良い。

環境

  • Windows10
  • Docker(WSL)
  • Python 3.10.7

コード

import logging
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import as_completed

# デバッグログ出力設定(どのプロセスでの実行かがわかるので便利)
logging.basicConfig(level=logging.DEBUG, format="%(processName)s: %(message)s")

# 1からmaxまで、かつmultipleの倍率のみ、値を出力する
def counter(index=-1, multiple=1, max=1):
    for i in range(1, max + 1):
        if i % multiple == 0:
            logging.debug(f"index={index}, number={i}")

    return index


# entry point
if __name__ == "__main__":

    # 値のループ用
    params = [
        {"multiple": 1, "max": 25},
        {"multiple": 2, "max": 8},
        {"multiple": 3, "max": 9},
        {"multiple": 4, "max": 20},
        {"multiple": 5, "max": 20},
    ]
    # プロセスの戻り値格納変数
    results = []

    # start the process pool
    with ProcessPoolExecutor(3) as executor:
        # マルチプロセスでcounterを実行
        futures = [executor.submit(counter, i, **param) for i, param in enumerate(params)]
        # 各プロセスの完了処理
        for future in as_completed(futures):
            # 終わった処理のindexを追加
            results.append(future.result())        
    
    # 処理が終わった順番を表示
    print(results)  

終わりに

リソースが貧弱な環境ではマルチスレッドの方が良いんじゃないかという雑な方針しかない人ですが、いつか役に立つことを願って、、

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0