Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

If you are a Dart developer looking to sharpen your skills, and get insight and tips on how to put that knowledge into practice, then this book is for you. You should also have a basic knowledge of HTML, and how web applications with browser clients and servers work, in order to build dynamic Dart applications.
Table of Contents (13 chapters)
12
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...