The usual pattern for a ReadWriteMutex is to use a semaphore and have the writer loop to acquire all the resources:
inline void write_lock() {
ScopedLock lock(acquire_mutex_);
for (size_t i=0; i < resource_count_; ++i) {
if (sem_wait(semaphore_) < 0) {
fprintf(stderr, "Could not acquire semaphore (%s)\n", strerror(errno));
}
}
}
This is fine except that you have to specify the resource count during semaphore initialization and arbitrarily choosing a resource count of 10 or 99999 does not feel right. Is there a better pattern that would allow “infinite” readers (no need for a resource count) ?
I found a solution: using
pthread_rwlock_t(ReaderWriterLock on Windows). These locks do not require a specific ‘max_readers_count’.I suspect that the implementation for this lock uses some kind of condition variable to lock readers entry when a writer needs to write and an atomic reader count.
Comparing this with my homebrewed semaphore based lock shows that writers are favored (they tend to run first).