I was reviewing the discussion on reusable barriers in "The Little Book of Semaphores". I wrote down this solution (below) before checking the answer in the book. Since the solution in the book is a bit more complex (two turnstiles) I am guessing I missed something obvious here. Can someone help me point out any problems with it?
# count = 0;
# mutex = semaphore(1);
# barrier = semaphore(0);
# rendezvous point
mutex.wait();
count = count + 1;
if (count == n) barrier.signal();
mutex.signal();
barrier.wait();
mutex.wait();
count = count - 1;
if (count != 0) barrier.signal();
mutex.signal();
# critical point
For reference, here's the solution proposed in the book using two turnstiles (barrier1 and barrier2)
# count = 0;
# mutex = semaphore(1);
# barrier1 = semaphore(0);
# barrier2 = semaphore(1);
# rendezvous point
mutex.wait();
count = count + 1;
if (count == n)
barrier2.wait();
barrier1.signal();
mutex.signal();
barrier1.wait();
barrier1.signal();
# critical point
mutex.wait();
count = count – 1;
if (count == 0)
barrier1.wait();
barrier2.signal();
mutex.signal();
barrier2.wait();
barrier2.signal();