Using multiple cores with isolates

In this recipe, we show you that the Dart VM uses multiple cores on a processor without having to specify anything to the VM. This allows a much better performance and throughput than if a Dart app could only use one processor.

How to do it...

Look at the following code for many_cores.dart (in the project using_isolates):

import'dart:isolate';

main() {
  int counter = 0;
  ReceivePortreceivePort = new ReceivePort();
  receivePort.listen((msg) {
    if (msg is SendPort) {
    msg.send(counter++);
  } else {
    print(msg);
    }
  });
  
  // starting isolates:
  for (var i = 0; i < 5; i++) {
  Isolate.spawn(runInIsolate, receivePort.sendPort);
  }
}

// code to run isolates
runInIsolate(SendPortsendPort) {
ReceivePortreceivePort = new ReceivePort(); ...

Get Dart: Scalable Application Development now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.