Reusable Barrier Algorithm

I am studying the reusable barrier algorithm from the book "The Little Book of Semaphores", which is available here http://greenteapress.com/semaphores/downey08semaphores.pdf

The puzzle is on page 31 (Basic Timing Patterns / Reusable Barrier), and I came up with a “solution” (or not) that is different from the solution from the book (two-phase barrier).

This is my "code" for each thread:

# n = 4; threads running
# semaphore = n max., initialized to 0
# mutex, unowned.

start:
    mutex.wait()
        counter = counter + 1
        if counter = n:
            semaphore.signal(4) # add 4 at once
            counter = 0
    mutex.release()
    semaphore.wait()
        # critical section
    semaphore.release()
goto start

This seems to work, I even entered different sleep timers in different sections of the threads, and they are still waiting for all the threads to appear before continuing with each cycle. Am I missing something? Is there a condition that this will not work?

I implemented this using the functions of the Semaphore and Mutex libraries on Windows.

Update:

starblue . , - mutex.release() semaphore.wait(), , semaphore.wait() , , N .

Sleep 3, http://pastebin.com/raw.php?i=FfXcCMZ3, , 3 , 1 2 , ( 1- ).

.

+3
1

, - .

+3

Source: https://habr.com/ru/post/1793205/


All Articles