Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop vs Break in Parallel.For

I have difficulty to understand loopState.Stop() and loopState.Break(). I have read MSDN and several posts about it but I am still confused.

What I understand is that every iteration partitioner gives remaining indexes for threads to process and loopState.Stop() stops all threads and loopState.Break() stops the current thread.

However lets consider the following situation:

Parallel.For(0, 100, (i, loopState) =>
{
    if (i >= 10) 
        loopState.Break();
    Debug.Write(i);
});

For this loop I have following result:

0 25 1 2 3 4 5 6 7 8 9 10 

I have no idea why in the result there is 10 and 25 numbers.

Anyone can help?

P.S. I have i5 520M CPU (2 cores => 4 Threads)

like image 234
Michał Jankowski Avatar asked Apr 28 '13 09:04

Michał Jankowski


People also ask

How do you break a parallel loop?

NET C# using the Stop method. It's not uncommon to break the execution of a for/foreach loop using the 'break' keyword. A for loop can look through a list of integers and if the loop body finds some matching value then the loop can be exited.

How do you stop a for loop parallel in C#?

In a parallel loop, you supply the CancellationToken to the method in the ParallelOptions parameter and then enclose the parallel call in a try-catch block.


1 Answers

loopState.Break() does not break the function like a return. So the line after the loopState.Break() will still be executed. After that scope has ended for that number, for checks if the loopState.Break() had been called. If so, all loops are allowed to continue until the number has been reached that called Break.

In your example, the loops with 0 till 24 will break at the same time as the loop 25 till 49 (and display their "breaking" numbers).

Loop 50..74 and 75..99 will not even get started because the second loop 25..49 has already aborted the whole for-operation, since their staring numbers are greater then the breaking number 10.

like image 191
Martin Mulder Avatar answered Sep 21 '22 16:09

Martin Mulder