Implementing an N process barrier using semaphores

Viewed 36804

I'm currently training for an OS exam with previous iterations and I came across this:

Implement a "N Process Barrier", that is, making sure that each process out of a group of them waits, at some point in its respective execution, for the other processes to reach their given point.

You have the following ops available:

init(sem,value), wait(sem) and signal(sem)

N is an arbitrary number. I can make it so that it works for a given number of processes, but not for any number.

Any ideas? It's OK to reply with the pseudo-code, this is not an assignment, just personal study.

4 Answers

I think this should also work, using only one semaphore (at least if the barrier is not required to be reusable)?

n = number of threads
barrier = Semaphore(1 - n)

barrier.signal()
barrier.wait()
barrier.signal()
Related