Created
April 24, 2022 06:47
-
-
Save hotdang-ca/d39e4a010b02db613b3ab06a52ca13c2 to your computer and use it in GitHub Desktop.
Isolate Fun 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:async'; | |
import 'dart:io'; | |
import 'dart:isolate'; | |
void main(List<String> arguments) async { | |
ReceivePort receivePort = ReceivePort(); | |
Isolate fooIsolate = await Isolate.spawn(foo, receivePort.sendPort); | |
Isolate barIsolate = await Isolate.spawn(bar, receivePort.sendPort); | |
Isolate fooBarIsolate = await Isolate.spawn(fooBar, receivePort.sendPort); | |
bool isFooFinished = false; | |
bool isBarFinished = false; | |
bool isFooBarFinished = false; | |
receivePort.listen((data) { | |
if ((data as String).contains('end')) { | |
if ((data as String).split('end')[1] == 'foo') { | |
isFooFinished = true; | |
if (isFooFinished && isBarFinished && isFooBarFinished) { | |
receivePort.close(); | |
} | |
} else if ((data as String).split('end')[1] == 'bar') { | |
isBarFinished = true; | |
if (isFooFinished && isBarFinished && isFooBarFinished) { | |
receivePort.close(); | |
} | |
} else if ((data as String).split('end')[1] == 'foobar') { | |
isFooBarFinished = true; | |
if (isFooFinished && isBarFinished && isFooBarFinished) { | |
receivePort.close(); | |
} | |
} | |
} | |
stdout.writeln((data as String)); | |
}); | |
} | |
void foo(SendPort sendPort) { | |
for (int x = 0; x <= 100; x++) { | |
if (x % 3 == 0) { | |
sendPort.send('$x: foo'); | |
} | |
} | |
sendPort.send('endfoo'); | |
} | |
void bar(SendPort sendPort) { | |
for (int x = 0; x <= 100; x++) { | |
if (x % 5 == 0) { | |
sendPort.send('$x: bar'); | |
} | |
} | |
sendPort.send('endbar'); | |
} | |
void fooBar(SendPort sendPort) { | |
for (int x = 0; x <= 100; x++) { | |
if (x % 3 == 0 && x % 5 == 0) { | |
sendPort.send('$x: foobar'); | |
} | |
} | |
sendPort.send('endfoobar'); | |
} | |
void runTimer(SendPort sendPort) { | |
int counter = 0; | |
Timer.periodic(Duration(seconds: 1), (Timer t) { | |
counter++; | |
String msg = 'notification ${counter.toString()}'; | |
stdout.write('Sending: $msg -'); | |
sendPort.send(msg); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment