9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FutureでDartのevent-loopを理解しようとしてるなう

Last updated at Posted at 2014-12-09

※とりあえず調べながら書着始めた感じなのであとでまとめます。
※たぶん間違いを含んでるとは思う

memo

  • event queuemicrotask queue がある
  • event queue contains many microtask queues な認識
  • NodeでいうとこのsetTimeout()とproess.nextTick()的な違い
  • FutureがFuture返すと、返されたFutureが何返すか待つ

event queuemicrotask 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() が実行されイベントループが開始されます。
まず最初に、全ての microtaskFIFO(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 の順番になってる。

  1. main()microtask(print/new Futuer**)を実行
  2. Future.microtaskで登録された#computation #2を、同じevent queue内で実行
  3. やる事なくなったんで次のevent queueであるcomputation #1Futureを実行
  4. またやる事なくなったんで、次のevent queueであるcomputation #3Futureを実行

的な感じだと理解してるなう。

参考資料

あとがき

9
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?