Skip to content

Instantly share code, notes, and snippets.

@damondouglas
Last active May 1, 2020 12:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save damondouglas/8620350 to your computer and use it in GitHub Desktop.
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.
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");
});
});
}
// == 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"); });
}
@damondouglas
Copy link
Author

@kevmoo
Copy link

kevmoo commented Sep 4, 2014

A couple of tweaks to spawn.dart?

Add imports

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

Fix use of initial reply

  initialReplyTo.send(port.sendPort);

@kevmoo
Copy link

kevmoo commented Sep 4, 2014

...and always, you get points for ending a file in a new line 😄

@e-oz
Copy link

e-oz commented Sep 14, 2014

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