Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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();
// send own sendPort to main isolate:
sendPort.send(receivePort.sendPort);

receivePort.listen((msg) {
  var k = 0;
  var max = (5 - msg) * 500000000;
    for (var i = 0; i < max; ++i) {
    i = ++i - 1...