Last active
May 1, 2020 12:55
-
-
Save damondouglas/8620350 to your computer and use it in GitHub Desktop.
Dart: Isolate Example [Courtesy: Forian Loitsch]. NOTE: This example is not maintained. Please see https://github.com/dartlang-italia/dart-libraries-samples/tree/master/isolate for a working example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void echo(SendPort initialReplyTo) { | |
var port = new ReceivePort(); | |
initialReplyTo(port.sendPort); | |
port.listen((msg) { | |
var data = msg[0]; | |
SendPort replyTo = msg[1]; | |
replyTo.send(data); | |
if (data == "bar") port.close(); | |
}); | |
} | |
Future sendReceive(SendPort port, msg) { | |
ReceivePort response = new ReceivePort(); | |
port.send([msg, response.sendPort]); | |
return response.first; | |
} | |
main() { | |
var response = new ReceivePort(); | |
Future<Isolate> remote = Isolate.spawn(echo, response.sendPort); | |
remote.then((_) => response.first).then((sendPort) { | |
sendReceive(sendPort, "foo").then((msg) { | |
print("received: $msg"); | |
return sendReceive(sendPort, "bar"); | |
}).then((msg) { | |
print("received another: $msg"); | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// == new file echo.dart. | |
void main(List<String> args, SendPort replyTo) { | |
replyTo.send(args[0]); | |
} | |
// == new file start.dart | |
main() { | |
var response = new ReceivePort(); | |
Future<Isolate> remote = Isolate.spawnUri(Uri.parse("echo.dart"), ["foo"], response.sendPort); | |
remote.then((_) => response.first) | |
.then((msg) { print("received: $msg"); }); | |
} |
A couple of tweaks to spawn.dart?
Add imports
import 'dart:async';
import 'dart:isolate';
Fix use of initial reply
initialReplyTo.send(port.sendPort);
...and always, you get points for ending a file in a new line 😄
Hello. I found this gist in google.
Please help he understand why code from this example don't want to be async.
I added
print('main');
after line 20,
sleep(new Duration(seconds: 5));
after line 29,
gist: https://gist.github.com/jamm/ae279f23cbd106e1d0fd
and result is:
main
// here we are waiting 5 seconds
received: foo
received another: bar
what's the case of spawning isolate if it waits for main thread?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Courtesy: https://groups.google.com/a/dartlang.org/forum/#!topic/misc/EVUMkZXFXtY