Closed2

Pythonの並列処理・並行処理

totsukatotsuka

並列処理

import time
from concurrent.futures import ThreadPoolExecutor


def task1(name, duration):
    print(f"{name} started")
    time.sleep(duration)
    print(f"{name} finished")


def task2(name, duration):
    print(f"{name} started")
    time.sleep(duration)
    print(f"{name} finished")


def task3(name, duration):
    print(f"{name} started")
    time.sleep(duration)
    print(f"{name} finished")


def main():
    with ThreadPoolExecutor(max_workers=3) as executor:
        executor.submit(task1, "タスク1", 3)
        executor.submit(task2, "タスク2", 3)
        executor.submit(task3, "タスク3", 3)


if __name__ == "__main__":
    main()
>>> python main.py
タスク1 started
タスク2 started
タスク3 started
タスク2 finished
タスク1 finished
タスク3 finished
totsukatotsuka

並行処理

先ほどのコードから呼び出すクラスを変えるだけ

ThreadPoolExecutor
このスクラップは2025/01/26にクローズされました