概念:允许多个读出,但只允许一个写入的需求。
读写锁与互斥量类似,不过读写锁允许更改的并行性,也叫共享互斥锁。
互斥量要么是锁住状态,要么就是不加锁状态,而且一次只有一个线程可以对其加锁。
读写锁可以有3种状态: 读模式下加锁状态、写模式加锁状态、不加锁状态。
读写锁使用步骤:
1、定义:pthread_rwlock_t rwlock;
2、初始化:
3、上锁
3.1申请读锁
3.2申请写锁
4、解锁
5、销毁读写锁
例子:要实现的功能是验证通过读写锁实现,读线程去访问共享资源时,允许其他的读线程去访问共享资源,但是不允许写线程去访问共享资源;当有写线程操作共享资源时,不允许写和读。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
//共享资源
int num=10;
//1、申请读写锁
pthread_rwlock_t rwlock;
void *readfun(void *arg)
{
while(1){
pthread_rwlock_rdlock(&rwlock);
printf(" %s 线程号%lu ,num=%d\n",__FUNCTION__,pthread_self(),num);
pthread_rwlock_unlock(&rwlock);
sleep(2);
}
return NULL;
}
void *writefun(void *arg)
{
//sleep(2);
while(1){
sleep(2);
pthread_rwlock_wrlock(&rwlock);
num++;
printf(" %s 线程号%lu ,num=%d\n",__FUNCTION__,pthread_self(),num);
pthread_rwlock_unlock(&rwlock);
sleep(4);
}
return NULL;
}
int main(int argc, char const *argv[])
{
//2、初始化读写锁
pthread_rwlock_init(&rwlock,NULL);
//循环创建8个线程
pthread_t tid[8];
int i=0;
for(i=0;i<8;i++)
{
if(i<5)
pthread_create(&tid[i],NULL,readfun,NULL);
else
pthread_create(&tid[i],NULL,writefun,NULL);
}
//循环回收线程资源
for(i=0;i<8;i++)
{
pthread_join(tid[i],NULL);//等待,阻塞
}
//销毁读写锁
pthread_rwlock_destroy(&rwlock);
return 0;
}
注意:读写锁适合于对数据结构的读次数比写次数多得多的情况。