Current-Users archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: pthread_cond_signal/broadcast: necessary to hold mutex?



On 3/23/26 9:50 PM, Thomas Klausner wrote:
      In this implementation, none of the functions enforce this
      requirement, but if the mutex is not held or independent mutexes
      are used the resulting behaviour is undefined.

The core design of condition variables with two threads A and B is as following.

Thread A does something like:
  acquire_mutex()
  for (;;) {
    if (!has_work())
      cv_wait();
    do_work();
  }

Thread B does something like:
  // Without mutex
  add_work();
  cv_signal();

Now add_work and has_work are not serialized because B doesn't hold the mutex. If thread A has just finished has_work, it is luck whether the cv_wait is run before or after cv_signal. If it is run after, you have potentially a dead lock condition. Requiring the mutex completely avoids the problem.

Now in principle there could be outside conditions that ensures the same constraints, but experience has shown that not to be true way too often. We used to assert this, but gave up after too many complains.

Joerg


Home | Main Index | Thread Index | Old Index