I'm looking for a way to use pthread rwlock structure with conditions routines in C++.
I have two questions:
First: How is it possible and if we can't, why ?
Second: Why current POSIX pthread have not implemented this behaviour ?
To understand my purpose, I explain what will be my use: I've a producer-consumer model dealing with one shared array. The consumer will cond_wait when the array is empty, but rdlock when reading some elems. The producer will wrlock when adding(+signal) or removing elems from the array.
The benefit of using rdlock instead of mutex_lock is to improve performance: when using mutex_lock, several readers would block, whereas using rdlock several readers would not block.
I assume that by "conditions", you mean "conditional variables". They're different things.
No, you cannot use a rwlock when waiting on a conditional variable. I cannot answer as to the "why", but that's the way POSIX has decided to do it. Perhaps just to keep things simple.
You can still get the behavior you want, however, by making your own rwlock class by using only a mutex and 2 conditional variables without using a POSIX rwlock:
getReadLock():
lock(mutex)
while(array.empty())
wait(readersCondVar, mutex)
readers++;
unlock(mutex)
releaseReadLock():
lock(mutex)
if (--readers == 0)
broadcast(writerCondVar, mutex) // or signal, if only 1 producer
unlock(mutex)
readerThread:
forever() {
getReadLock()
read()
releaseReadLock()
}
getWriteLock():
lock(mutex)
while(readers) {
wait(writerCondVar, mutex)
}
releaseWriteLock():
broadcast(readersCondVar, mutex)
unlock(mutex)
writerThread():
forever() {
getWriteLock()
write()
releaseWriteLock()
}
Simple and does what you want.