Previous | Next --- Slide 48 of 62
Back to Lecture Thumbnails
hrw

Why are the first and third barrier necessary?

amolakn

@hrw If the code weren't being run in a loop, you're right in that only the second would be necessary. But consider the fact that it is being run in a loop.

The second barrier is pretty clear, let's have each thread finish before we do our check in order to ensure that our check is accounting for all threads. But consider the next iteration if the first and third barrier weren't there. For this example, I'm going to say we have two threads, thread A and thread B.

Let's start with a example of what could happen if the first barrier weren't there:

Thread A | Thread B

Enter loop

diff = 0.0f

Compute

diff += myDiff

Hit barrier 2

            Enter loop

            diff = 0.0f

            Compute

            diff += myDiff

            Hit barrier 2

Do you see what went wrong here? The thread A computed myDiff and added it to diff, but the thread B then reset diff to 0 again hence undoing whatever thread A just did in its execution.

I want to leave this open for discussion, can anyone else explain why the third barrier is necessary?