AllenDowney / LittleBookOfSemaphores

LaTeX source and supporting code for The Little Book of Semaphores, by Allen Downey.
273 stars 77 forks source link

Unclear problem in 'Reusable barrier problem #1' #9

Open viralmutant opened 5 years ago

viralmutant commented 5 years ago

The problem described in the Section 3.7.2 for the non-solution in 3.7.1 is

If the n − 1th thread is interrupted at this point, and then the nth thread comes through the mutex, both threads will find that count==n and both threads will signal the turnstile. In fact, it is even possible that all the threads will signal the turnstile.

Isn't this also true for the working solution described in 3.6.4 ? The text under that head says

It might seem dangerous to read the value of count outside the mutex. In this case it is not a problem Isn't that the same problem described in section 3.7.2 ? What would be the problem if all the threads signal but none of them is in wait yet ?

Spoonbender commented 2 years ago

The fact that two threads will see that count == n and both will call barrier.signal() doesn't change the functionality of the one-time barrier discussed in 3.6.x., since the code doesn't reuse this barrier - so its final state doesn't matter, since the guarantees made by the barrier are held. It matters in 3.7.1 because if the turnstile is over-signaled then its internal counter will not be zero when we re-use the barrier and hit line 9 again, which means the barrier will be opened before all N threads reached it.

viralmutant commented 2 years ago

The fact that two threads will see that count == n and both will call barrier.signal() doesn't change the functionality of the one-time barrier discussed in 3.6.x., since the code doesn't reuse this barrier - so its final state doesn't matter, since the guarantees made by the barrier are held. It matters in 3.7.1 because if the turnstile is over-signaled then its internal counter will not be zero when we re-use the barrier and hit line 9 again, which means the barrier will be opened before all N threads reached it.

Yup !! Got it. Thanks But I have 1 more doubt in 'Preloaded Turnstile' solution. Since we have signal(n) construct, we can very well re-use a single turnstile, right ? Instead of having turnstile and turnstile2 ? Or is it that they are explaining how to re-use Barrier in general and what goes inside the python Barrier class(as explained in the next section), b'coz re-usable barrier object in python is from where my confusion stemmed.