leastBusyThread property

  1. @protected
Thread leastBusyThread

Gets the thread that is currently the least busy.

This method finds the thread with the fewest active tasks among the ready threads. If no thread is ready, it selects the first thread in the list.

Returns the least busy Thread.

Implementation

@protected
Thread get leastBusyThread {
  var models = threads.where((model) => model.isReady).toList();
  if (models.isEmpty) models.add(threads.first);

  // Find the minimum number of active tasks among the ready models
  int minActiveTasks = models.map((model) => model.activeTasks).reduce(min);
  // Filter the models to include only those with the minimum number of active tasks
  List<Thread> leastActiveTaskModels =
      models.where((model) => model.activeTasks == minActiveTasks).toList();
  // Randomly select one model from the list of models with the minimum number of active tasks
  return leastActiveTaskModels[
      Random().nextInt(leastActiveTaskModels.length)];
}