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.
参考資料
- Python Documentation 18.5.9. asyncio での開発 — Python 3.6.8 ドキュメント
- Pythonの非同期通信(asyncioモジュール)入門を書きました Pythonの非同期通信(asyncioモジュール)入門を書きました - ゆくゆくは有へと
- 一番詳しいがちょっと難しい。。
- Pythonを取り巻く同期/非同期の話 Pythonをとりまく並行/非同期の話
- すごくわかりやすい. 用語をちゃんと説明してくれている
- 参考資料集も充実してる pyconjp2017/reference.rst at master · tell-k/pyconjp2017 · GitHub
- Async IO in Python: A Complete Walkthrough Async IO in Python: A Complete Walkthrough – Real Python
- 英語だけどよくまとまっていそう. 参考文献リストもよさげ.
- Pythonにおける非同期処理: asyncio逆引きリファレンス Pythonにおける非同期処理: asyncio逆引きリファレンス - Qiita
- 「マルチスレッド」、「マルチプロセス」、「ノンブロッキング」の違いについて
- async ioの基本的な使い方
- Pythonの非同期I/O(asyncio)を試す Pythonの非同期I/O(asyncio)を試す - Qiita
- Sleep Sortを実装している
- プロセスとスレッドの違い イケてるエンジニアになろうシリーズ 〜メモリとプロセスとスレッド編〜 - もろず blog
- これもプロセスとスレッドの違い プロセスとスレッドの明確な違いを比較表で説明
- Pythonのジェネレータ、コルーチン、ネイティブコルーチン、そしてasync/await Pythonのジェネレータ、コルーチン、ネイティブコルーチン、そしてasync/await | POSTD