Code
dart
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));
}