I'm really new to Dart and also to programming. I'm trying to develop a a command-line program in Dart using isolates. My intention is to compare it's performance againt the same program, but written in Java with threads.
The Dart program looks like this so far:
main.dart
import "dart:async"; import "dart:isolate"; main() { var rPort1 = new ReceivePort(); var rPort2 = new ReceivePort(); var p1 = 0; rPort1.listen((partial) { print("p1 ${partial}"); p1 = partial; rPort1.close(); }); var p2 = 0; rPort2.listen((partial) { print("p2 ${partial}"); p2 = partial; rPort2.close(); }); Isolate.spawnUri(new Uri.file("MyIsolate.dart"), [arg0, ...], rPort1.sendPort); Isolate.spawnUri(new Uri.file("MyIsolate.dart"), [arg0, ...], rPort2.sendPort); var p3 = p1 + p2; print("p3 ${p3}"); }
myIsolate.dart
import "dart:async"; import "dart:isolate"; main(args, SendPort port) { var partial = 0; // ... do stuff ... // args are used and partial is updated port.send(partial); }
The output looks like this:
p3 0
p1 -0.1168096561671553
p2 0.023709338284264223
As you can see the return values of each isolate comes after the main isolate has finished it's execution. What I want is to use the result of the isolates to further calculation in the main.
I don't know what I'm missing. I'm sure is something very stupid, but I cannot move forward on this problem. In Java is simple to get the result value of each thread, but in Dart I can't figure how to do this in isolates.
Any ideas?
You have to wait until all streams (from your ports) are complete. One of ways for doing that is something like that:
For your task, if you're waiting for exact values, you may define only Futures for these values you need, and complete them without waiting for your isolates (and their streams) to finish.
For doing this, just move
c*.complete(<value>)
to corresponding listen() callback. Something like that (not tested):