我得到了一种读/写锁的实现,如下所示。请注意,在函数的开头,有一个pthread_mutex_lock
调用。如果它仍然使用pthread_mutex_lock
一次,那么使用读/写锁有什么好处。它比简单地使用更好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;
}
}