According to Open Group Base Specifications Issue 7, IEEE Std 1003.1-2008,
a single condition variable (pthread_cond_t
) shouldn't be used along different mutexes (pthread_mutex_t
) in pthread_cond_wait()
while at least one thread is waiting on this condition variable: eg. pthread_cond_wait(&cond1, &mutex1)
can't be used in parallel with pthread_cond_wait(&cond1, &mutex2)
: this behavor is unspecified.
But it is not specified if using a single mutex with multiple condition variables is allowed, eg: pthread_cond_wait(&cond1, &mutex1)
in parallel with pthread_cond_wait(&cond2, &mutex1)
.
I think such construction should be avoided to allow safe (two way)
dynamic binding [...] formed between that mutex and condition variable
Could someone comment on this issue ?
It's perfectly fine to use the same mutex for multiple condition variables, just not the reverse.
One way to think about this is: Part of the contract of pthread_cond_wait
is that when the calling thread awakens from its wait, it will own the locked mutex, which makes sense only if there's just one mutex associated with the condition variable.
To see why you might want to do this, imagine a design where you have a number of global counters protected by a single mutex (user count, # of open files, etc.). You could then quite reasonably have multiple condition variables you might want to wait on, all associated with that single mutex:
pthread_cond_wait(&usercount_lessthan_limit_cond, &global_mutex);
...
pthread_cond_wait(&openfilecount_lessthan_limit_cond, &global_mutex);
...etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With