tags:

views:

70

answers:

2

How can a barrier be implemented with semaphores in Java. Will the following pseudo code work? How can it be written using java Semaphore class.

N is the number of threads to be waited for at the barrier. EveryoneHasReachedBarrier is a 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);
   }
}
+2  A: 

Just use a CountDownLatch or a CyclicBarrier.

brunodecarvalho
Ah ... but the OP essentially wants to know to implement these using the Semaphore class ... as homework.
Stephen C
He can look at the source for those two and learn something useful in the process.
brunodecarvalho
@bruno - or not learn anything at all by just copying. The best way to understand concurrent programming by going through the mental process of trying to work it out yourself.
Stephen C
+1 for undeniable truth.
brunodecarvalho
A: 

1) Your pseudo-code doesn't use semaphores so it is not a solution.

2) It doesn't correspond to the way that Java primitive mutex / wait / notify work.

3) It probably wouldn't work anyway. Since you release the mutex before acquiring the condition there is potential for a race condition. (It is not entirely clear that this is the case because the semantics of your "primitives" are open to interpretation.)

Hint: What you need to do is read the javadocs for the Semaphore class thoroughly and then try to map them onto the problem you are trying to solve.

Stephen C
thanks, just one question. can it be done using one semaphore object?
Ajex
@Ajex - since this is homework, my response is as follows: "Good question. What do **you** think the answer is? Why don't you try and see if you can make it work with one Semaphore?"
Stephen C
I think a single semaphore variable cannot track multiple threads. It has no way to know which all threads came.
Ajex
If there are threads A, B, C, D, I need to know if all have arrived. Not A, B, C, A
Ajex
So try a solution with 2 semaphores then.
Stephen C
@Ajex - a thread cannot arrive twice. The first time it arrives it blocks until the other threads arrive.
Stephen C
oh. ok. So one of the two you mentioned should be for mutual exclusion and the other for counting.
Ajex
@Ajex - I didn't say you had to use either one or two. I'm saying **try it out**. The point of homework is that you learn by **doing** not by asking someone else for the answer!!!
Stephen C
I understand. Will try it out. Thanks a lot for your help. I feel motivated now.
Ajex