Created
March 8, 2019 08:43
-
-
Save wtoalabi/6a17b2f33c9e3f4951fdf5fb9fad16ce to your computer and use it in GitHub Desktop.
Spawning Isolates in Dart
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
import 'dart:io'; | |
import 'dart:async'; | |
import 'dart:isolate'; | |
Isolate isolate; | |
main() async{ | |
stdout.writeln('spawning isolate...'); | |
await start(); | |
stdout.writeln('press enter key to quit...'); | |
await stdin.first; | |
stop(); | |
stdout.writeln('goodbye!'); | |
exit(0); | |
} | |
void start() async { | |
ReceivePort receivePort= ReceivePort(); //port for this main isolate to receive messages. | |
isolate = await Isolate.spawn(runTimer, receivePort.sendPort); | |
receivePort.listen((data) { | |
stdout.write('RECEIVE: ' + data + ', '); | |
}); | |
} | |
void runTimer(SendPort sendPort) { | |
int counter = 0; | |
Timer.periodic(new Duration(seconds: 1), (Timer t) { | |
counter++; | |
String msg = 'notification ' + counter.toString(); | |
stdout.write('SEND: ' + msg + ' - '); | |
sendPort.send(msg); | |
}); | |
} | |
void stop() { | |
if (isolate != null) { | |
stdout.writeln('killing isolate'); | |
isolate.kill(priority: Isolate.immediate); | |
isolate = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment