Skip to content

Instantly share code, notes, and snippets.

@Cliabhach
Last active May 2, 2022 07:50
Show Gist options
  • Select an option

  • Save Cliabhach/59807b527beccd985539b1b710f537cd to your computer and use it in GitHub Desktop.

Select an option

Save Cliabhach/59807b527beccd985539b1b710f537cd to your computer and use it in GitHub Desktop.
Testing out interaction between Dart Futures and Dart Isolates
/// SPDX-License-Identifier: Apache-2.0
/// Based on source code in https://levelup.gitconnected.com/fluttering-dart-futures-and-isolates-6b4bce6d804b
import 'dart:math';
import 'dart:isolate';
class Cat {
var index;
var meowDelay;
Cat(int index, int meowDelay) {
this.index = index;
this.meowDelay = meowDelay;
}
/// Wait a given number of seconds, meow, and then run `afterMeow`.
void meow(Future<void> afterMeow) async {
await Future.delayed(Duration(seconds: meowDelay));
print('Kitten $index: Meow!');
await afterMeow;
print('Kitten $index has finished.');
}
}
Future<void> createMeowFuture(int index) async {
return print('Just meowed! ($index/10)');
}
void main() async {
final timeInterval = 10;
final random = Random.secure();
// Request 10 meows.
await doLoop(random, timeInterval);
// TODO: Wait for all of those meows to finish
print('Just finished!!');
}
/// Correct
// Kitten 0: Meow!
// Just meowed! (0/10)
// Kitten 1: Meow!
// Just meowed! (1/10)
// Kitten 2: Meow!
// Kitten 3: Meow!
// Just meowed! (2/10)
// Kitten 4: Meow!
// Kitten 5: Meow!
// Just meowed! (3/10)
// Kitten 6: Meow!
// Kitten 7: Meow!
// Just meowed! (4/10)
// Just meowed! (5/10)
// Kitten 8: Meow!
// Kitten 9: Meow!
// Just meowed! (6/10)
// Just meowed! (7/10)
// Just meowed! (8/10)
// Just meowed! (9/10)
// Just finished!!
/// Incorrect
// Just meowed! (0/10)
// Just meowed! (1/10)
// Just meowed! (2/10)
// Just meowed! (3/10)
// Just meowed! (4/10)
// Just meowed! (5/10)
// Just meowed! (6/10)
// Just meowed! (7/10)
// Just meowed! (8/10)
// Just meowed! (9/10)
// Just finished!!
Future<void> doLoop(Random random, int timeInterval) async {
for(var i=0; i<10; i++) {
final kitten = Cat(i, random.nextInt(timeInterval));
await Isolate.spawn(kitten.meow, createMeowFuture(i));
}
}
@dinakar-m
Copy link

@Cliabhach below is just idea... i dont know if help or not!

i think this is just basic problem about

  1. Run multiple threads by child or by multiple thread...
  2. After point 1. completes know the by call back (await etc.)

try understanding the below part code....
https://itnext.io/minimalist-guide-to-isolates-in-dart-flutter-dd5bdee031e
image

one more idea in your case you should understand how and why you want spawn is there is better design you can write your code..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment