tech-userlevel archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
Re: Q about pthread condition variable usage - mixing interlocks
On Thu, 8 Apr 2021 10:47:09 -0700
Jason Thorpe <thorpej%me.com@localhost> wrote:
> Is there ANY situation where, for a given pthread condition variable, that
> using a different mutex as the interlock in two different calls to
> pthread_cond_wait() would EVER be legitimate usage? I cannot come up with
> any scenario in which this would be appropriate, but who knows what some
> crazy applications might do.
I'd say NO. Condition variables are there so one can implement a monitor
with the pthread routines and ALL monitor functions need to lock the same
interlock for proper monitor function. (Also the reason to be holding the
lock when calling signal or broadcast. In fact, if the call to signal or
broadcast needs to hold the mutex, then having different mutexes on the
cond wait queue could easily cause the problem of the signal thread holding
the wrong mutex for the thread on the head of the wait queue.)
Had I designed the interface, I'd have had the cond init function require
the lock at init time and throw an error if that lock was not held by the
calling thread to cond_wait() and not even passed the lock in the cond_wait()
call.
The next question is "does any code out there use two different interlocks
for the same cond variable?" And if they did, what would be the result?
In looking at the code in src/lib/libpthread, it is interesting to note
that in pthread_cond_timedwait() (which is called by pthread_cond_wait()
with a very large time) does the following when the thread is awake again:
pthread_mutex_lock(mutex);
So, if we were using different mutexes here, it might be possible to have
the lock return the error EDEADLK. And by not testing for this, there is
a possibility that pthread_cond_*wait() could return without the mutex locked
and not returning an error. (I'm quite sure I could write code that should
detect a deadlock.)
It appears to me that the code is expecting only one mutex and that it is
held at cond_wait time and thus should have no problem re-locking the mutex.
--Phil
Home |
Main Index |
Thread Index |
Old Index