Skip to content

Instantly share code, notes, and snippets.

@pulsar256
Created January 18, 2021 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pulsar256/924531d870d3ba136329bd6c09ae1212 to your computer and use it in GitHub Desktop.
Save pulsar256/924531d870d3ba136329bd6c09ae1212 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:io';
import 'dart:math';
StreamController<int> controller = StreamController();
Future<void> main() async {
final paths = [for (var i = 0; i < 100; i++) "path $i"];
paths.iterator.throttledForEach(10, (path) async {
final script = ["-c", "sleep ${Random().nextInt(10)}"];
final process = await Process.start("sh", script);
final returnCode = await process.exitCode;
print("finshed $path with return code $returnCode");
});
}
extension on Iterator {
void throttledForEach(int parallelFutures, Function onData) async {
final semaphores = StreamController<int>();
while (parallelFutures-- > 0) {
semaphores.add(1);
}
await for (var _ in semaphores.stream) {
if (!moveNext()) break;
try {
onData(current);
} catch (_) {} finally {
semaphores.add(1);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment