views:

264

answers:

3

We're covering multithreaded programming in a class I'm taking. The professor offered a bonus question that I have been trying, to no avail, to figure out:

Each of processes P0, P1, P2 and P3 have to wait for the other three to cross or reach a particular synchronization point in their code, and only then may that process cross its own synchronization point.

I already know how to answer the question with four semaphores, the hard part is doing it with only one semaphore.

Any suggestions or hints as to how to proceed?

A: 

Just initialize your semaphore at -4 if it's not a binary one.

attwad
ok an explanation for the down-voting?
attwad
I didn't down vote you but I suspect it was because you can't initialize semaphores with negative values. In POSIX the value is unsigned and the Windows docs specifically state a value of 0 or greater.
Duck
this is quite limitative: i often need an inverse semaphore and i could never find one. while not possible due to software limitations, his answer is perfectly logical. a bit of explanation would have been welcome though.
Adrien Plisson
It's a useful construct and if you search around you can find various implementations but I get the feeling there is no consensus on what the exact semantics should be.
Duck
That's the solution I came up with... but as the other commenters (and my professor) have pointed out it's not allowed.
KidDaedalus
A: 

You are a little light on the constraints imposed on your solution but see The Little Book of Semaphores and read through the sections on barriers. That should give you some ideas.

Duck
Thank you for the resource, that should be quite helpful.
KidDaedalus
A: 

Turns out the professor had meant to say that you could use two semaphores instead of one. He believes, as I do after having thought about the problem for a while, that it is impossible to do with a single semaphore.

KidDaedalus
That's why I commented on your not mentioning much about constraints. You can do it with one semaphore and mutex protecting a counter but I wasn't sure if you could use mutexes or if they would count as a second semaphore.
Duck