4
votes

I was watching Operating system course part 2 lecture 2 video 17. In this lecture she mentioned that the data-structure of condition variable contains mutex reference and list of waiting threads.

I want to know if it is possible to use the same condition with different mutexes?

For example: I have 2 wait statements

  1. wait(mutex1, condition_A)
  2. wait(mutex2, condition_A) //condition is the same in both

If the answer to the above question is yes, then will these two statements create two condition variables or one? Note: Lecture mentioned only one mutex reference.

1

1 Answers

2
votes

I guess it depends on the implementation.

POSIX says:

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. Once all waiting threads have been unblocked (as by the pthread_cond_broadcast() operation), the next wait operation on that condition variable shall form a new dynamic binding with the mutex specified by that wait operation.

So you can you the same condition variable with difference mutexes, but not at the same time.

With regards to C++, cppreference.com says:

Calling this function if lock.mutex() is not the same mutex as the one used by all other threads that are currently waiting on the same condition variable is undefined behavior.

So it seems to have the same requirements as POSIX condition variables.