0

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!

Kim
  • 65
  • 6

1 Answers1

1

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.

mariusm
  • 1,483
  • 1
  • 11
  • 26
  • [You can build a semaphore from a mutex and a conditional variable](http://stackoverflow.com/a/4793662/412080). Both of which can be process-shared and placed in the shared memory, hence providing an inter-process communication mechanism. – Maxim Egorushkin Nov 30 '16 at 10:22
  • @MaximEgorushkin sure, you can build one out of another (it's a performance overkill), but I would like to see standard/native CV with IPC, e.g. I don't see such an option in pthread_cond_init. – mariusm Nov 30 '16 at 19:24
  • 1
    Process shared mutexes and condition variables have been standard for decades now. http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_condattr_setpshared.html – Maxim Egorushkin Nov 30 '16 at 19:35
  • @MaximEgorushkin somehow I can't find it in Linux manuals.. but it exists in pthread.h, thanks! – mariusm Nov 30 '16 at 19:41