How to realize a queue in dart?

Viewed 3295

I want to set up a queue of functions in Darts. Queuing should be asynchronous, allowing multiple functions to run concurrently. However, a maximum of three functions should be executed simultaneously. How can I achieve this?

I already tied working off a list but i am struggeling at adding a limit on same time running functions

List<String> queue = new List();

main(){
  queue.add("...");
  queue.add("...");
  queue.add("...");

  for(String q in queue){
    await crawl(q);
  }
}

crawl(String) async{
   ...
}
1 Answers

I would use a queue:

import "dart:collection";
final queue = Queue<String>();
main() {
  queue
    ..add("...")
    ..add("...")
    ..add("...");
  while (queue.isNotEmpty) {
    await crawl(queue.removeFirst());
  }
}

crawl(String x) async {
  .... queue.add(...) ...
}

This should work. It will not do concurrent crawling because await each operation. If you want concurrent crawling, I recommend being a little more clever. Look for worker pools or similar structures to ensure that you only have a certain number of operations running at the same time.

Related