Pythonの非同期asyncioについてのメモ

ノンブロッキングな非同期の要素

  • コルーチンオブジェクト(async/await)
  • コルーチンをスケジュール管理するオブジェクト(Task もしくはFuture)
  • 複数コルーチンを実行するloop

非同期処理の用語

  • asyncioモジュールはノンブロッキングな非同期処理に使う
    • シングルスレッドでの非同期処理である
      • マルチプロセスはcpu、マルチスレッドはプロセスの中でのプログラムの単位でメモリ共有
  • 関数をコルーチンにするにはasyncをつける
    • コルーチンとは関数の途中で処理を保留し、状態を保持して後から再開することができる関数のこと
  • コルーチンを実行するにはawaitが必要? ここ怪しいな
  • コルーチンを実行するだけでは非同期にならない. スケジュール調整と実行するloopが必要.
  • コルーチンを実行するスケジュールを立てるにはtaskもしくはfutureにする必要がある
    • taskはコルーチンを非同期処理するために賢くスケジュール実行してくれる(時間がかかる処理を待つ間、他の処理を実行)
    • asyncio.gatherやasyncio.waitを使ってfuture化できる
    • task化、future化することで、コルーチンの結果を取り出す、引数を渡す、callbackを設定するなどができる
  • スケジュール実行するにはloopが必要である
    • asyncio.run で生成と終了までしてくれる
    • loop = asyncio.new_event_loop()で明示的に作ることもできる
  • Task
    Tasks are used to schedule coroutines concurrently. When a coroutine is wrapped into a Task with functions like asyncio.create_task() the coroutine is automatically scheduled to run soon.
  • Future
    A Future is a special low-level awaitable object that represents an eventual result of an asynchronous operation. When a Future object is awaited it means that the coroutine will wait until the Future is resolved in some other place. Future objects in asyncio are needed to allow callback-based code to be used with async/await. Normally there is no need to create Future objects at the application level code. Future objects, sometimes exposed by libraries and some asyncio APIs, can be awaited.

参考資料