I got one implementation of read/write locks which is below. Notice that in the beginning of the functions, there is a pthread_mutex_lock call. If it uses pthread_mutex_lock once anyway, then what is the benefit of using read/write locks. How is it better than simply using pthread_mutex_lock?
int pthread_rwlock_rlock_np(pthread_rwlock_t *rwlock)
{
pthread_mutex_lock(&(rwlock->mutex));
rwlock->r_waiting++;
while (rwlock->r_wait > 0)
{
pthread_cond_wait(&(rwlock->r_ok), &(rwlock->mutex));
}
rwlock->reading++;
rwlock->r_waiting--;
pthread_mutex_unlock(&(rwlock->mutex));
return 0;
}
int pthread_rwlock_wlock_np(pthread_rwlock_t *rwlock)
{
pthread_mutex_lock(&(rwlock->mutex));
if(pthread_mutex_trylock(&(rwlock->w_lock)) == 0)
{
rwlock->r_wait = 1;
rwlock->w_waiting++;
while (rwlock->reading > 0)
{
pthread_cond_wait(&(rwlock->w_ok), &(rwlock->mutex));
}
rwlock->w_waiting--;
pthread_mutex_unlock(&(rwlock->mutex));
return 0;
}
else
{
rwlock->wu_waiting++;
while (pthread_mutex_trylock(&(rwlock->w_lock)) != 0)
{
pthread_cond_wait(&(rwlock->w_unlock), &(rwlock->mutex));
}
rwlock->wu_waiting--;
rwlock->r_wait = 1;
rwlock->w_waiting++;
while (rwlock->reading > 0)
{
pthread_cond_wait(&(rwlock->w_ok), &(rwlock->mutex));
}
rwlock->w_waiting--;
pthread_mutex_unlock(&(rwlock->mutex));
return 0;
}
}
The
rwlock->mutexmutex is used to protect the state of therwlockstructure itself, not the state of whatever the reader/writer lock may be protecting in your target program. This mutex is held only during the time the lock is acquired or released. It is entered into just briefly, to avoid corrupting the state that is needed for “bookkeeping” of the reader/writer lock itself. In contrast, the reader/writer lock may be held for an extended period of time by the callers performing the actual reads and writes on the structure the lock protects.