Skip to content
Dart

Isolates (True Parallelism)

Run code in separate isolates for CPU-bound work.

By EZ4Code Team
isolateparallelconcurrency

Code

import 'dart:isolate';

// CPU-heavy function
int heavyComputation(int n) {
  var sum = 0;
  for (var i = 0; i < n; i++) {
    sum += i * i;
  }
  return sum;
}

Future<int> runInIsolate(int n) async {
  final result = await Isolate.run(() => heavyComputation(n));
  return result;
}

// Two-way communication
Future<void> spawnWorker() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(_workerEntry, receivePort.sendPort);

  // Wait for worker's send port
  final workerSendPort = await receivePort.first as SendPort;

  final responsePort = ReceivePort();
  workerSendPort.send(['compute', 1000000, responsePort.sendPort]);
  final result = await responsePort.first;
  print('Result: $result');
}

void _workerEntry(SendPort mainSendPort) {
  final receivePort = ReceivePort();
  mainSendPort.send(receivePort.sendPort);

  receivePort.listen((message) {
    final [cmd, arg, replyPort] = message as List;
    if (cmd == 'compute') {
      (replyPort as SendPort).send(heavyComputation(arg as int));
    }
  });
}

void main() async {
  print(await runInIsolate(1000000));
}

Explanation

Isolates are Dart's threads — they don't share memory, communicate via message passing (like actors). Isolate.run (Dart 2.19+) is the simplest API — runs a function in a fresh isolate and returns the result. For long-lived workers, use spawn with SendPort/ReceivePort for two-way messaging. Isolates are the only way to do true parallel CPU work — async/await is single-threaded (concurrent but not parallel).

More Dart Snippets