Barrier Implementation in Java

How can you implement a semaphore barrier in Java. Will the following pseudo code work? How can this be written using the Javaava semaphore class.

N- the number of threads expected at the barrier. EveryoneHasReachedBarrier- conditional variable.

Aquire(mutex)
m = m + 1;
if(m != N)
{ 
    Release(mutex);
    Aquire(EveryoneHasReachedBarrier);
}
else
{
   m = 0;
   Release(mutex);
   for(i=0; i<N; i++)
   {
       Release(EveryoneHasReachedBarrier);
   }
}
+3
source share
2 answers

1) Your pseudocode does not use semaphores, so it is not a solution.

2) This does not match how primitive mutex / wait / notify Java works.

3) This probably won't work. Since you release the mutex before acquiring a condition, there is a chance of a race condition. (It is not entirely clear that this is so because the semantics of your "primitives" are open to interpretation.)

. , javadocs Semaphore, , .

0

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


All Articles