与互斥量类似,但读写锁允许更高的并行性。其特性为:写独占,读共享。
读写锁状态:
一把读写锁具备三种状态:
1.读模式下加锁状态(读锁)
2.写模式下加锁状态(写锁)
3.不加锁状态
读写锁特性:
1.读写锁是“写模式加锁”时,解锁前,所有对该锁加锁的线程都会被阻塞。
2.读写锁是“读模式加锁”时,如果线程以读模式对其加锁会成功;如果以写模式加锁会阻塞。
3.读写锁是“读模式加锁”时,既有试图以写模式加锁的线程,也有试图以读模式加锁的线程。那么读写锁会阻塞随后的读模式锁请求。优先满足写模式锁。读锁、写锁并行阻塞,写锁优先级高。
主要应用函数:
pthread_rwlock_init函数
初始化一把读写锁。
pthread_rwlock_destroy函数
销毁一把读写锁。
pthread_rwlock_rdlock函数
加写锁。
pthread_rwlock_wrlock函数
加读锁。
pthread_rwlock_tryrdlock函数
尝试加读锁。
pthread_rwlock_trywrlock函数
尝试加写锁。
pthread_rwlock_unlock函数
解锁。
以上7个函数的返回值都是:成功返回0,失败直接返回错误号。
pthread_rwlock_t 类型 用于定义一个读写锁变量
pthread_rwlock_t rwlock;
示例代码rwlock.c
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int counter;
pthread_rwlock_t rwlock;
void *th_write(void *arg)
{
int t;
int i=(int)arg;
while(1){
t=counter;
usleep(1000);
pthread_rwlock_wrlock(&rwlock);
printf("=======write %d: %lu: counter=%d ++counter=%d\n",i,pthread_self(),t,++counter);
pthread_rwlock_unlock(&rwlock);
usleep(5000);
}
return NULL;
}
void *th_read(void *arg)
{
int i=(int)arg;
while(1){
pthread_rwlock_rdlock(&rwlock);
printf("-------------------read %d:%lu:%d\n",i,pthread_self(),counter);
pthread_rwlock_unlock(&rwlock);
usleep(900);
}
return NULL;
}
int main(void)
{
int i;
pthread_t tid[8];
pthread_rwlock_init(&rwlock,NULL);
for(i=0;i<3;i++)
pthread_create(&tid[i],NULL,th_write,(void *)i);
for(i=0;i<5;i++)
pthread_create(&tid[i+3],NULL,th_read,(void *)i);
for(i=0;i<8;i++)
pthread_join(tid[i],NULL);
pthread_rwlock_destroy(&rwlock);
return 0;
}