Open1

並列処理

derwindderwind

ChatGPT 曰く、以下のようにすれば CPU コア数より多くのタスクを順次実行できるらしい:

import multiprocessing
import time

# タスクをシミュレートするための関数
def task_proc(task_id):
    print(f"Task {task_id} started.")
    time.sleep(2)  # タスク処理時間のシミュレーション
    print(f"Task {task_id} completed.")
    return task_id

if __name__ == "__main__":
    tasks = [i for i in range(1, 11)]  # 実行するタスクのリスト (例: 1から10まで)

    with multiprocessing.Pool(4) as pool:
        results = pool.map(task_proc, tasks)  # 並列処理を行う

    print("All tasks completed.")

終了処理をきっちりやるバージョン:

import multiprocessing
import time

# タスクをシミュレートするための関数
def task_proc(task_id):
    print(f"Task {task_id} started.")
    time.sleep(2)  # タスク処理時間のシミュレーション
    print(f"Task {task_id} completed.")
    return task_id

if __name__ == "__main__":
    tasks = [i for i in range(1, 11)]  # 実行するタスクのリスト (例: 1から10まで)

    pool = multiprocessing.Pool(4)  # 4つのCPUコアを使用してプールを作成
    results = pool.map(task_proc, tasks)  # 並列処理を行う

    pool.close()  # プールへの新しいタスクの追加を停止
    pool.join()   # 全てのタスクが完了するまで待機

    print("All tasks completed.")