地方エンジニアの学習日記

興味ある技術の雑なメモだったりを書いてくブログ。たまに日記とガジェット紹介。

【Python】非同期タスク生成

await はイベントループへの制御の委譲であり、この間に別のタスクが動いて状態を変える可能性がある。

これはマルチスレッドのプリエンプティブな並行処理とは異なるが、状態共有をすると同様に危険。

asyncio.create_task() を使ったタスク生成

import asyncio

async def say_hello(name):
    await asyncio.sleep(1)
    print(f"Hello, {name}!")

async def main():
    task1 = asyncio.create_task(say_hello("Alice"))
    task2 = asyncio.create_task(say_hello("Bob"))

    # 並行に実行される
    await task1
    await task2

asyncio.run(main())

asyncio.gather()を使う

import asyncio

async def work(i):
    await asyncio.sleep(0.5)
    print(f"Task {i} done")
    return i * 2

async def main():
    results = await asyncio.gather(*(work(i) for i in range(5)))
    print("Results:", results)

asyncio.run(main())

asyncio.create_task() + キャンセル

import asyncio

async def never_finish():
    try:
        while True:
            print("Working...")
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print("Task was cancelled!")
        raise

async def main():
    task = asyncio.create_task(never_finish())
    await asyncio.sleep(3)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("Handled cancellation in main")

asyncio.run(main())

realpython.com