0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonのasync/await構文による非同期設計:イベントループと並行処理の洗練

Posted at

概要

非同期処理は、Pythonが本来得意としなかった領域を、
async/awaitasyncio の導入によって強力にサポートするようになった。

この構文は単なるスレッド代替ではなく、
イベントループベースでの協調的マルチタスクの宣言的設計を可能にする。

本稿では、asyncio による非同期設計の構造、使用上の注意点、
並行処理によるスケーラビリティ強化の実践パターンを体系的に解説する。


1. async/await の基本構文

import asyncio

async def greet():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(greet())
  • async def: 非同期関数を定義(coroutineオブジェクトを返す)
  • await: 非同期関数の実行を一時停止・再開可能にする

イベントループ上での協調的な並行処理が実現される


2. 複数の非同期処理を同時に走らせる

async def task(name, delay):
    print(f"{name} started")
    await asyncio.sleep(delay)
    print(f"{name} done")

async def main():
    await asyncio.gather(
        task("A", 1),
        task("B", 2),
        task("C", 1)
    )

asyncio.run(main())
  • gather() によって複数のタスクを並行実行
  • 実行順に依存しない処理の効率化に有効

3. 非同期 vs 並列処理の違い

非同期(asyncio) 並列(threading/multiprocessing)
シングルスレッド内のタスク切り替え 複数スレッド/プロセスによる同時実行
I/O向き(ネットワーク、DB等) CPUバウンド処理向き
軽量・メモリ効率良好 高負荷タスクにも耐えられる

適材適所で使い分けるのがPython設計の鍵


4. 非同期I/Oの応用例

✅ 非同期HTTPリクエスト(aiohttp)

import aiohttp
import asyncio

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

urls = ["https://example.com", "https://python.org"]

async def main():
    results = await asyncio.gather(*(fetch(u) for u in urls))

asyncio.run(main())

→ 同期コードに比べて圧倒的に高速なI/Oスループットを実現可能


5. 非同期ジェネレータ / コンテキスト

✅ 非同期イテレータ

async def countdown(n):
    while n > 0:
        yield n
        n -= 1
        await asyncio.sleep(1)

✅ 非同期コンテキストマネージャ

async with aiohttp.ClientSession() as session:
    ...

async/await構文はイテレータやwith構文にも完全対応


6. よくある誤用と対策

❌ await を忘れて coroutine を実行

async def run(): return 1
result = run()  # ❌ 実行されない

→ ✅ await run() または asyncio.run(run()) が必要


❌ 同期処理のまま重いI/Oをawaitで包む

await open("big_file.txt").read()  # ❌ 同期I/Oのまま

→ ✅ aiofilesやaiomysql等、非同期対応ライブラリを用いる


❌ イベントループの多重作成

loop = asyncio.get_event_loop()
loop.run_until_complete(...)  # ✅ 一度だけ使う

→ ✅ 高水準API asyncio.run() を使うのが推奨


結語

async/await は、Pythonにおける**「明示的な非同期制御の構文化」**を実現する。

  • イベントループによる効率的なI/O処理
  • 宣言的かつ構造的な非同期関数の設計
  • asyncioエコシステムによる高性能アプリケーションの基盤

Pythonicとは、“暗黙の制御を構文で意図に昇華する”ことであり、
async/await はその思想を並行処理の領域において明確に体現する手段である。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?