Using Isolates for Parallel Execution

This example demonstrates how to use isolates for parallel execution in Dart.

import 'dart:async';
import 'dart:io';
import 'dart:convert';

void isolateEntry(SendPort sendPort) {
  var receivePort = ReceivePort();
  sendPort.send(receivePort.sendPort);
  
  receivePort.listen((message) {
    if (message is int) {
      var result = message * message;
      sendPort.send(result);
    }
  });
}

Future<void> main() async {
  var receivePort = ReceivePort();
  await Isolate.spawn(isolateEntry, receivePort.sendPort);

  var sendPort = await receivePort.first as SendPort;

  print('Sending numbers to isolate for squaring:');
  for (var i = 1; i <= 5; i++) {
    sendPort.send(i);
    var squared = await receivePort.first;
    print('Squared: $squared');
  }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *