概要
Python × 非同期IOなアプリケーションで色々あったので調査メモ
本編
非同期IO環境で同期IOを発行する場合、asyncio.to_thread または loop.run_in_executor を使用することで、イベントループをブロックせずに同期処理を実行できます。asyncio.to_thread を使用する場合、生成されるのは LWP(Lightweight Process) ではなく、スレッドです。具体的には、asyncio.to_thread は、同期I/Oを非同期的に実行するためにスレッドプールを使いますが、そのスレッドが LWP としてカーネルによって管理されることが多いです。
import asyncio # 同期IOの例 def blocking_io(): # ここで重い処理(例:ファイル操作、データベースアクセスなど) print("Starting blocking I/O...") import time time.sleep(3) # 3秒間の同期処理 print("Blocking I/O done.") # 非同期IOの中で同期IOを使う async def main(): print("Before blocking I/O") # 同期I/Oを非同期スレッドで実行 await asyncio.to_thread(blocking_io) print("After blocking I/O") # イベントループで実行 asyncio.run(main())