※とりあえず調べながら書着始めた感じなのであとでまとめます。
※たぶん間違いを含んでるとは思う
memo
-
event queueとmicrotask queueがある -
event queuecontains manymicrotask queues な認識 - NodeでいうとこのsetTimeout()とproess.nextTick()的な違い
- FutureがFuture返すと、返されたFutureが何返すか待つ
event queue と microtask queue
As the following figure shows, when main() exits, the event loop starts its work. First, it executes any microtasks, in FIFO order. Then it dequeues and handles the first item on the event queue. Then it repeats the cycle: execute all microtasks, and then handle the next item on the event queue.
超意訳。間違ってたらごめんてへぺろ
(次の図が示すように、) main() が実行されイベントループが開始されます。
まず最初に、全ての microtask が FIFO(First-In-First-Out) の順番で実行されます。
そして一番最初のevent queueが取り出され処理されます。
そして、これら(全てのmicrotask queueを実行し、次のevent queueに移る)が繰り返されます。
つまり何
import "dart:async";
void main() {
print('main #1');
new Future(()=> print('computation #1')).then((_) => print('then #1 - 1')).then((_)=> print('then #1 - 2'));
new Future.microtask(()=> print('comupataion #2')).then((_) => print('then #2 -1')).then((_)=> print('then #2 - 2'));
new Future(()=> print('computation #3')).then((_) => print('then #3 - 1')).then((_)=> print('then #3 - 2'));
print('main #2');
}
この結果が
main #1
main #2
comupataion #2
then #2 -1
then #2 - 2
computation #1
then #1 - 1
then #1 - 2
computation #3
then #3 - 1
then #3 - 2
になる。
main #1(#2)に関しては最初に出力されるのはそんなに難しくない。
次に、new Future() で作った computation #1 ではなくて、
new Future.microtask() で作った computaion #2 が先に出力されてるのがポイント。
new Future() は内部では Timer.run() で登録していて、
NodeでいうsetTimeout(hoge,0) 的な動きをする。
new Future.microtask() は内部では scheduleMicrotask というトップレベル関数を叩いてて、
Nodeでいうprocess.nextTick() 的な動きをする。
FIFOなのでcomputation #1 -> computation #3 の順番になってる。
-
main()のmicrotask(print/new Futuer**)を実行 -
Future.microtaskで登録された#computation #2を、同じevent queue内で実行 - やる事なくなったんで次の
event queueであるcomputation #1のFutureを実行 - またやる事なくなったんで、次の
event queueであるcomputation #3のFutureを実行
的な感じだと理解してるなう。
参考資料
- https://www.packtpub.com/web-development/mastering-dart
-
https://www.dartlang.org/articles/event-loop/
- ↑This is GOOD. So, this is GOD な資料
あとがき
- いろいろあとで書こうとしてましたが The Event Loop and Dart の翻訳を書いた んで、そっち見てください。