Background
I have a piece of code which is highly parallelizable and I found that most of the time I am using only one core at 100% while the rest does nothing. To tackle this I've tinkered with multithreading, implementing semaphores and what not to realize that Parallel.For() is fine grained and more efficient than any of my solutions.
The Code
To simplify I will only write the pieces of code structurally important.
int sharedResource = 0;
for (int i = 0; i < someMax; i++)
{
for (int j = 0; j <= i; j++)
{
if (someCondition(i, j))
sharedResource += someFunction(i, j);
else break;
}
}
All of the ambiguously named functions are more or less just mathematical equations and are of time complexity O(1).
Important Details
Pay attention to the inner loop that has the variable i as upper boundary as well as the summation variable named sharedResource. The execution order in this case is not important as addition is commutative and I don't see any obvious reason for Amdahl's Law to apply as all instance combinations (i, j) of both loops can be calculated independently.
Question
Is it smart to use a nested Parallel.For() loop in this scenario or should I only use it instead of the outer loop (or only on the inner respectively)?
The only thing that concerns me is the sharedResource as I don't get a lot of in-depth insight of how Parallel.For() works from the documentation. Another important thing is that if I do use two Parallel.For() loops some instances will finish almost instantly due to the break while others will take much more time. Will it be able to balance this?