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.
C++0x is getting multithreading support, and that support includes a new type called condition_variable_any:
There is an explanation of how to implement condition_variable_any here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html#gen_cond_var
but at this link it is named gen_cond_var. The magic thing about condition_variable_any is that it will wait on anything that has lock() and unlock() members. Once you have condition_variable_any, then all you need is a rwlock. The link above also introduces shared_mutex and shared_lock and shows example code doing what you want:
The above document is somewhat dated. There is a more up-to-date implementation and description of shared_mutex / shared_lock here:
http://howardhinnant.github.io/shared_mutex http://howardhinnant.github.io/shared_mutex.cpp
All of this is implemented on top of POSIX pthreads. I hope to get the shared-locking stuff into a C++ technical report (tr2), but of course there is no guarantee of that.
There are several RWLocks implemented on top of mutexes and condvars. Pick any one and add some condvars for your custom needs.
To solve issue signaled by Doomsday one have to check again condition after
grab_mutex
and beforewait_on_condition
:For what you want, you need to just have 1 set of rwlock and 1 set of mutex/cond variable, pseudo code (though you'll need the usual loops on the posix cond variables)
I'd guess condition variables only works with mutexes, because waiting or signalling a conditions needs mutual exclusiveness.
I have the same requirement as you needed.
Here is my solution:
Wrap pthread_rwlock_t
Usage
Producer
Consumer
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:
Simple and does what you want.