最終更新:2021-08-11 (水) 10:01:43 (989d)  

Python/コルーチン
Top / Python / コルーチン

https://docs.python.org/ja/3/library/asyncio-task.html

概要

  • イベントループを使った非同期処理のときに使う
  • エントリポイントが複数箇所あるため、一度呼び出されても中断でき、その場所からまた再開できる

時間のかかる処理

  • await: この行で時間のかかる処理をしますという指示
  • awaitのある行が中断ポイントかつエントリ(再開)ポイント

コルーチン

Python/コルーチン関数?

Python/コルーチンオブジェクト?

  • コルーチン関数?を呼び出すと返ってくるオブジェクト
  • いつかは完了する計算または I/O 操作 (通常はその組み合わせ) を表す
  • Python/コルーチンオブジェクト?Python/イベントループ内でのみ実行が可能

使い方

result = await future (result = yield from future)

  • suspends the coroutine until the future is done, then returns the future's result, or raises an exception, which will be propagated.

result = await coroutine (result = yield from coroutine)

  • wait for another coroutine to produce a result

return expression

  • produce a result to the coroutine that is waiting for this one using await or yield from.

メモ

  • コルーチンオブジェクトはイベントループ内でのみ実行が可能
  • ジェネレータベースのコルーチンはyield構文を使う代わりに、PEP 380で導入されたyield from構文を使う

コルーチン

Python/Task

  • asyncio.Task
  • コルーチンを実行するFutureオブジェクト?

参考

関連

参考