读写锁是互斥锁的升级版
对于同一个变量我们对此同时写会导致数据不同步,但是却可以同时读,因此读是并行的,写是串行的
正确的使用读写锁可以提高并发量
下面是一个经典的例子,同样也是几个小孩数数,但是这次却有小孩记录读了多少
一共有八个线程,一个全局变量,三个变量写此变量,五个变量不定时读变量
代码如下:
#include<pthread.h>
#include <stdlib.h>
int num=0;
void w_num(void *arg);
void r_num(void *arg);
pthread_rwlock_t wr_lock;
int main(void)
{
pthread_rwlock_init(&wr_lock,NULL);
pthread_t w_tid[3],r_tid[5];
for(int i=0;i<3;i++)
{
pthread_create(&w_tid[i],NULL,w_num,NULL);
}
for(int i=0;i<5;i++)
{
pthread_create(&r_tid[i],NULL,r_num,NULL);
}
for(int i=0;i<3;i++)
{
pthread_join(w_tid[i],NULL);
}
sleep(2);
for(int i=0;i<5;i++)
{
pthread_join(r_tid[i],NULL);
}
pthread_rwlock_destroy(&wr_lock);
return 0;
}
void w_num(void *arg)
{
int tmp;
for(int i=0;i<5;i++)
{
pthread_rwlock_wrlock(&wr_lock);
tmp=num;
tmp++;
num=tmp;
printf("%d\n",tmp);
pthread_rwlock_unlock(&wr_lock);
usleep(5);
}
}
void r_num(void *arg)
{
for(int i=0;i<5;i++)
{
pthread_rwlock_rdlock(&wr_lock);
printf("the num = %d\n",num);
pthread_rwlock_unlock(&wr_lock);
usleep(rand()%5);
}
}
结果分析,因为有三个变量进行写,总共15次,所以数数到15,然后五个进程不定时进行读
读写锁和互斥锁是类似
定义读写锁变量使用pthread_rwlock_t wr_lock;
初始化读写锁pthread_rwlock_init(&wr_lock,NULL);
销毁读写锁pthread_rwlock_destroy(&wr_lock);
读写锁其实是一把锁,不是读锁和写锁,这一点我们是要搞清楚的
写操作因为写的时候是不允许其他线程进行操作的,所以和互斥锁一样的,只是函数名字不一样
for(int i=0;i<5;i++)
{
pthread_rwlock_wrlock(&wr_lock);//加写锁
tmp=num;
tmp++;
num=tmp;
printf("%d\n",tmp);
pthread_rwlock_unlock(&wr_lock);//解写锁
usleep(5);
}
读操作是允许多个变量同时读,是并行的
for(int i=0;i<5;i++)
{
pthread_rwlock_rdlock(&wr_lock);//加读锁
printf("the num = %d\n",num);
pthread_rwlock_unlock(&wr_lock);//解读锁
usleep(rand()%5);//不定时查看全局变量
}