Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any example for dart's `spawnUri(...)` in library "dart:isolate"?

There is a spawnUri(uri) function in dart:isolate, but I don't find any example. I have guessed its usage, but failed.

Suppose there are 2 files, in the first one, it will call spawnUri for the 2nd one, and communicate with it.

first.dart

import "dart:isolate";

main() {
  ReceivePort port = new ReceivePort();
  port.receive((msg, _) {
    print(msg);
    port.close();
  });
   var c = spawnUri("./second.dart");
   c.send(["Freewind", "enjoy dart"], port.toSendPort());
}

second.dart

String hello(String who, String message) {
   return "Hello, $who, $message";
}

void isolateMain(ReceivePort port) {
  port.receive((msg, reply) => reply.send(hello(msg[0], msg[1]));
}

main() {}

But this example doesn't work. I don't know what's the correct code, how to fix it?

like image 707
Freewind Avatar asked Dec 21 '22 03:12

Freewind


2 Answers

Here is a simple example that works with Dart 1.0.

app.dart:

import 'dart:isolate';
import 'dart:html';
import 'dart:async';

main() {
  Element output = querySelector('output');

  SendPort sendPort;

  ReceivePort receivePort = new ReceivePort();
  receivePort.listen((msg) {
    if (sendPort == null) {
      sendPort = msg;
    } else {
      output.text += 'Received from isolate: $msg\n';
    }
  });

  String workerUri;

  // Yikes, this is a hack. But is there another way?
  if (identical(1, 1.0)) {
    // we're in dart2js!
    workerUri = 'worker.dart.js';
  } else {
    // we're in the VM!
    workerUri = 'worker.dart';
  }

  int counter = 0;

  Isolate.spawnUri(Uri.parse(workerUri), [], receivePort.sendPort).then((isolate) {
    print('isolate spawned');
    new Timer.periodic(const Duration(seconds: 1), (t) {
      sendPort.send('From app: ${counter++}');
    });
  });
}

worker.dart:

import 'dart:isolate';

main(List<String> args, SendPort sendPort) {
  ReceivePort receivePort = new ReceivePort();
  sendPort.send(receivePort.sendPort);

  receivePort.listen((msg) {
    sendPort.send('ECHO: $msg');
  });
}

Building is a two-step process:

  1. pub build
  2. dart2js -m web/worker.dart -obuild/worker.dart.js

See the complete project here: https://github.com/sethladd/dart_worker_isolates_dart2js_test

like image 112
Seth Ladd Avatar answered Jan 12 '23 01:01

Seth Ladd


WARNING : This code is out of date.

Replace your second.dart with the following to make it work :

import "dart:isolate";

String hello(String who, String message) {
  return "Hello, $who, $message";
}

main() {
  port.receive((msg, reply) => reply.send(hello(msg[0], msg[1])));
}
like image 21
Alexandre Ardhuin Avatar answered Jan 12 '23 01:01

Alexandre Ardhuin