Dart Isolates
Dart Isolates
In the Async Intro chapter, you learned that Dart runs your code on one thread.
Futures are great for waiting, for example for a timer or a file.
But some tasks are not waiting, they are working hard, like doing a big calculation or reading a very large text.
A big calculation keeps the thread busy, and nothing else can run until it is done.
In an app, this makes the screen freeze.
An isolate solves this problem.
What Is an Isolate?
An isolate is a separate worker that runs Dart code next to your main program.
Every Dart program already runs in one isolate, called the main isolate.
You can start more isolates to do heavy work at the same time.
Each isolate has its own memory, so isolates do not share variables.
That is why it is called an isolate: it is isolated (kept apart) from the others.
The only way to share data is to send a message, for example the result of the work.
Isolate.run()
The easiest way to use an isolate is Isolate.run() from the dart:isolate library.
It does three things for you:
- It starts a new isolate.
- It runs your function in that isolate.
- It sends the result back as a future, and closes the isolate.
This example adds all the numbers from 1 to 100 million in a new isolate:
Example
import 'dart:isolate';
int sumNumbers() {
int sum = 0;
for (int i = 1; i <= 100000000; i++) {
sum += i;
}
return sum;
}
Future<void> main() async {
print('Starting the heavy work...');
int result = await Isolate.run(sumNumbers);
print('The sum is $result');
}
Try it Yourself »
Result:
Starting the heavy work...
The sum is 5000000050000000
Since Isolate.run() returns a future, you use await to get the result.
The Main Program Keeps Running
While the isolate is working, the main isolate is free to do other things.
Timer.periodic() from dart:async runs a function again and again, with a waiting time between each run.
In this example, a timer adds 1 to ticks every 100 milliseconds, while the heavy work runs in another isolate:
Example
import 'dart:async';
import 'dart:isolate';
int countPrimes(int max) {
int count = 0;
for (int n = 2; n <= max; n++) {
bool isPrime = true;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
isPrime = false;
break;
}
}
if (isPrime) count++;
}
return count;
}
Future<void> main() async {
int ticks = 0;
final timer = Timer.periodic(Duration(milliseconds: 100), (t) {
ticks++;
});
int primes = await Isolate.run(() => countPrimes(5000000));
timer.cancel();
print('Primes up to 5 million: $primes');
print('Did the timer run? ${ticks > 0}');
}
Try it Yourself »
Result:
Primes up to 5 million: 348513
Did the timer run? true
The timer could keep counting, because the main isolate was not busy.
Now look at the same program without an isolate.
The calculation runs in the main isolate, so the timer cannot run at all until the calculation is done:
Example
import 'dart:async';
int countPrimes(int max) {
int count = 0;
for (int n = 2; n <= max; n++) {
bool isPrime = true;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
isPrime = false;
break;
}
}
if (isPrime) count++;
}
return count;
}
void main() {
int ticks = 0;
final timer = Timer.periodic(Duration(milliseconds: 100), (t) {
ticks++;
});
int primes = countPrimes(5000000);
timer.cancel();
print('Primes up to 5 million: $primes');
print('Did the timer run? ${ticks > 0}');
}
Try it Yourself »
Result:
Primes up to 5 million: 348513
Did the timer run? false
Send Values to the Isolate
To give values to the function, wrap the call in an anonymous function, like () => countWords(text).
The values are copied into the new isolate:
Example
import 'dart:isolate';
int countWords(String text) {
return text.split(' ').length;
}
Future<void> main() async {
String story = 'Once upon a time there was a little cat';
int words = await Isolate.run(() => countWords(story));
print('The story has $words words');
}
Try it Yourself »
Result:
The story has 9 words
Isolates Do Not Share Memory
When an isolate changes a variable, it only changes its own copy.
The main isolate does not see the change:
Example
import 'dart:isolate';
int visitors = 0;
Future<void> main() async {
int inside = await Isolate.run(() {
visitors += 10;
return visitors;
});
print('Visitors in the new isolate: $inside');
print('Visitors in the main isolate: $visitors');
}
Try it Yourself »
Result:
Visitors in the new isolate: 10
Visitors in the main isolate: 0
To get data back from an isolate, return it from the function.
When to Use an Isolate
Most programs do not need isolates.
- Use async and await when your program is waiting for something, like a timer, a file or the internet.
- Use an isolate when your program is working hard on a long calculation.
Starting an isolate also takes a little time, so use it only for work that takes a long time.
Note: Isolate.run() does not work in Dart programs that run in a web browser.