18

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)

7 Answers 7

14

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.

6
  • So loopState.Break() exits all threads? I use to thing that loopState.Stop() does it. Apr 28, 2013 at 10:47
  • To clarify my previous comment: I understand now how the first two loops stops but why the two other threads do not even starts? Is Break able to terminate more then one thread? If so how it does it? Apr 28, 2013 at 10:54
  • 1
    See for a good answer about Stop vs Break: stackoverflow.com/questions/8818203/… Apr 28, 2013 at 11:03
  • @MichałJankowski The other two don't start probably because they just don't get time to - if you put a Thread.Sleep(1) just before loopState.Break() they sometimes do start executing. Apr 28, 2013 at 11:06
  • @svick+Michal: I adjusted my answer. I wanted my anwer as simple as possible. But this was too simple. Thanx for the update. Apr 28, 2013 at 11:10
5

From the documentation of Break():

Break may be used to communicate to the loop that no other iterations after the current iteration need be run. For example, if Break is called from the 100th iteration of a for loop iterating in parallel from 0 to 1000, all iterations less than 100 should still be run, but the iterations from 101 through to 1000 are not necessary.

What this means is that the current iteration will still finish (so 10 gets printed). Break() also isn't capable of time travel, so the 25 will stay printed. What Break() means is that no new iterations beyond 10 will be started.

5

Simplest answer:

both stop and break prevent new iterations to be started. Both ensure that started iteration finish.

difference - stop - aborts the iteration it called in and break doesn't.

4

if (i >= 10) loopState.Break(); will still continue the current iteration. So 10 is printed.

However, iterations (i >= 10) after the loopState.Break() called will not start.

But why 25 is printed? The following image will explain why. Since you have 4 threads, 0-99 will be divided as 4.

1st thread has: 0-24.
2nd thread has: 25 - 49.
3rd thread has: 50 - 74.
4th thread has: 75 - 99.

Based on my understanding, each thread will loop the numbers itself. According to this post, it says

Additional iterations may be run, if they were already started when Break was called.

As the 2nd thread has started almost the same time as the 1st thread, so 0, 25 is printed. Then if (i >= 10) loopState.Break(); is called when looping 25 in the 2nd thread.

The loops in 3rd and 4th thread did not start before the Break() is called hence any number greater than 10 did not print.

image ref: http://www.albahari.com/threading/part5.aspx

2

All methods from static Parallel class returns ParallelLoopResult.This object has two properties - IsCompleted and LowestBreakIteration

When we use loopState.Break(), LowestBreakIteration returns an integer that represents the lowest iteration from which the Break statement was called

When we use loopState.Stop(), LowestBreakIteration Returns null

0

Break ensures that all iterations that are currently running will be finished.

Stop just terminates everything.

2
0
void Log(string prefix, bool isBreak=false) 
{
    var msg = isBreak ? " Break" : "";
    Console.WriteLine($"{prefix} task: {Task.CurrentId.ToString().PadLeft(3,'0')} {msg}");

}
long lockFlag=0;
Parallel.For(0, 130, (i, loopState) =>
{
    if (i >= 10 && Interlocked.Read(ref lockFlag)==0)
    {
        lockFlag=Interlocked.Increment(ref lockFlag);
        loopState.Break();
        //Statement after break will still execute for current iteration
        Log(i.ToString().PadLeft(3,'0'),true);
    }
    else
    {
      Log(i.ToString().PadLeft(3,'0')); 
    }
});   

enter image description here

Tasks "8904" keep running to complete all iterations less than 25. Obviously if iterations have already completed that represent values greater than 25, then there will be no way of rolling back.

If you do want to terminate the loop as soon as possible and don’t care about guaranteeing that all prior iterations have completed, then ParallelLoopState has another method called Stop(). The Stop method attempts to end the loop as soon as possible—once issued, no loop task will start a new iteration

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.