Use Parallel.ForEach for grouped by-divisor work items

This commit is contained in:
Marek Lemańczyk committed 2025-10-12 00:36:20 +02:00
1 parent 4f73d89716
commit 9c378db18f
1 file changed
+10 -6
@@ -272,7 +272,7 @@ public static class MersenneNumberDivisorByDivisorTester
return; return;
} }
Task[] workers = new Task[workerCount]; (int Start, int End)[] workerRanges = new (int, int)[workerCount];
int totalPrimeCount = filteredPrimes.Count; int totalPrimeCount = filteredPrimes.Count;
int baseGroupSize = totalPrimeCount / workerCount; int baseGroupSize = totalPrimeCount / workerCount;
int remaining = totalPrimeCount % workerCount; int remaining = totalPrimeCount % workerCount;
@@ -288,17 +288,21 @@ public static class MersenneNumberDivisorByDivisorTester
int startIndex = groupStartIndex; int startIndex = groupStartIndex;
int endIndex = startIndex + groupSize; int endIndex = startIndex + groupSize;
workerRanges[workerIndex] = (startIndex, endIndex);
groupStartIndex = endIndex; groupStartIndex = endIndex;
}
workers[workerIndex] = Task.Run(() => ParallelOptions parallelOptions = new()
{ {
for (int candidateIndex = startIndex; candidateIndex < endIndex; candidateIndex++) MaxDegreeOfParallelism = workerCount
};
Parallel.ForEach(workerRanges, parallelOptions, range =>
{
for (int candidateIndex = range.Start; candidateIndex < range.End; candidateIndex++)
{ {
ProcessPrime(filteredPrimes[candidateIndex]); ProcessPrime(filteredPrimes[candidateIndex]);
} }
}); });
} }
Task.WaitAll(workers);
}
} }