The below program is for understanding isolates
in dart
. The compute
method is passed to the spawned isolate. Inside of compute
method summation is performed but when List.generate
is used the compute
function doesn't finish the execution because the print("The total sum is : $sum");
statement is never called.
Instead of using List.generate
if we use simple for loop
(commented line of code in compute()
) the sum
is calculated and also displayed.
import "dart:isolate";
void main(final List<String> args) async {
print("Entering main");
final model = ModelClass(35000, 100);
await Isolate.spawn<ModelClass>(compute, model);
print("Exiting main");
}
void compute(final ModelClass model) {
int sum = 0;
for (int value in List.generate(model.iteration, (index) => index)) {
sum += value * model.multiplier;
}
// for (int index = 0; index < model.iteration; index++) {
// sum += index * model.multiplier;
// }
print("The total sum is : $sum");
}
class ModelClass {
final int iteration;
final int multiplier;
ModelClass(this.iteration, this.multiplier);
}
Why when we use List.generate
to generate a list
and iterate over it the compute
function doesn't finish execution?