Search code examples
cdesign-patternsposixmutexcondition-variable

In POSIX, why can't a single condvar be used with multiple mutexes?


Why is the behavior undefined when a POSIX condition variable is used with multiple mutexes?

Excerpt from the 2018 edition:

When a thread waits on a condition variable, having specified a particular mutex to either the pthread_cond_timedwait() or the pthread_cond_wait() operation, a dynamic binding is formed between that mutex and condition variable that remains in effect as long as at least one thread is blocked on the condition variable. During this time, the effect of an attempt by any thread to wait on that condition variable using a different mutex is undefined

I suppose it's because of some kind of implementation detail of some specific system, so can someone confirm or refute it?

C11 (and C17) condition variables don't seem to have such limitation, and why?


Solution

  • C11 (and C17) condition variables don't seem to have such limitation,

    I agree that C11 and C17 seem not to document any limitation on the mutex(es) used with cnd_wait or cnd_timedwait. However, they do permit these functions to fail, and one plausible reason they might fail is that a different mutex is specified than another thread currently waiting on the same CV specified.

    and why?

    I can only speculate about the standard committee's motivations and thought process. Possibly members wanted to allow implementations that do not have such a limitation, and they assumed that other implementations would simply exercise their option to fail as needed. Possibly it was simply an oversight.

    It is both ordinary for condition variable implementations and appropriate for condition variable usage patterns to expect that multiple threads do not concurrently wait on a CV with different mutexes. POSIX is by no means unique in its restriction:

    • C++ std::condition_variable has a restriction analogous to POSIX's
    • Java objects' monitors and implementations of java.util.concurrent.locks.Condition are inherently associated with specific locks, so one cannot even express trying to use one with different locks at the same time.
    • Python threading.Condition objects are also associated with specific locks.