Kim
Kim

Reputation: 75

Condition Variable vs Semaphore example

I'm having a hard time solving this homework problem. Does calling x.signal() in one thread and later x.wait() in another thread produce a different result when x is a condition variable and when x is a semaphore?

My guess is that in this particular case it won't matter if x is a condition variable or a semaphore.

Thank you for help!

Upvotes: 0

Views: 2544

Answers (1)

mariusm
mariusm

Reputation: 1678

Semaphore has a state protected by atomic operations, meanwhile the condition variable (CV) does not have its own state and is not even protected (the usual assumption is that the program has its own, more complicated shared state than just an integer and thus needs to maintain it "manually").

The correct use of CV requires that both signal and wait operations are protected (surrounded by the associated mutex locking), otherwise the waiting thread may miss the signalling. So the program needs to ensure the proper locking sequence on CVs.

Meanwhile semaphore operations are hidden from developer, and the code is simpler and cannot go wrong in ways CVs can, but it also maintains very simple/small shared state with very specific operations.

Upvotes: 1

Related Questions