Gabriel Gabriel - 1 month ago 18
Dart Question

Is Dart's async really async?

Given the following code

import 'dart:async';

var total = 0;
final iterations = 10000000;

Future add() async {
print('starting add -> $total');

for (var i = 0; i < iterations; i++) {
total += 1;
}

print('ending add -> $total');
}

Future sub() async {
print('starting sub -> $total');

for (var i = 0; i < iterations; i++) {
total -= 1;
}

print('ending sub -> $total');
}

void main(List<String> args) {
add();
sub();
print('done');
}


which generates the following output

done
starting add -> 0
ending add -> 10000000
starting sub -> 10000000
ending sub -> 0


I wonder if
async
calls are really executed in an async fashion.

It looks like all
async
methods run in a second thread which is always the same, so they are async for their callers, but not for each other.

Am I right? If so, how can I execute multiple functions in an really async fashion (just like creating new threads)?

Answer

This is how async works. There is only one thread and an event queue where tasks are enqueued. When the previous sync execution is completed, then the next task in the queue is executed.

If you need parallel execution you can leverage isolates.

See also