读者:只读数据区中的数据
写者:只往数据区中写数据
要求:
(1)允许多个读者同时执行读操作;
(2)不允许读者、写者同时操作;
(3)不允许多个写者同时操作。
在编写多线程的时候,有种很常见的场景,就是公共数据被修改的机会比较少(即写的几率小),相对写,读的几率反而高,在读的过程中,往往伴随着查找的操作,中间耗时很长。给这种代码段加锁,会极⼤大地降低我们程序的效率。故引入读写锁来解决多读少写的问题。
自旋锁与互斥锁:
自旋锁与互斥锁比较类似,它们都是为了解决对某项资源的互斥使用。无论是互斥锁,还是自旋锁,在任何时刻,最多只能有一个保持者,也就说,在任何时刻最多只能有一个执行单元获得锁。但是两者在调度机制上略有不同。对于互斥锁,如果资源已经被占用,资源申请者只能进入睡眠状态。但是自旋锁不会引起调用者睡眠,如果自旋锁已经被别的执行单元保持,调用者就一直循环在那里看是否该自旋锁的保持者已经释放了锁。
读写锁实际上是一把自旋锁。
未加读写锁之前:
参考代码:
#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
int value=0;
void* writer(void *arg)
{
while(1)
{
sleep(2);
value++;
}
return (void*)0;
}
void* reader(void *arg)
{
while(1)
{
printf("write value:%d\n",value);
}
return (void*)0;
}
int main()
{
pthread_t tid1;
pthread_t tid2;
pthread_create(&tid1,NULL,writer,NULL);
pthread_create(&tid2,NULL,reader,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
由于读的几率比较高,所以数据得不到及时更新。如下:
运行结果:
加了读写锁之后,如果新读者到:
①无读者、写者,新读者可以读;
②有写者等待,但有其它读者正在读,则新读者也可以读;
③有写者写,新读者等待。
如果新写者到:
①无读者,新写者可以写;
②有读者,新写者等待;
③有其它写者,新写者等待。
#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
pthread_rwlock_t rwlock;
int value=0;
void* writer(void *arg)
{
while(1)
{
sleep(1);
if(pthread_rwlock_wrlock(&rwlock)!=0)
{
printf("reader is reading\n");
}
value++;
printf("write value:%d\n",value);
pthread_rwlock_unlock(&rwlock);
}
return (void*)0;
}
void* reader(void *arg)
{
while(1)
{
sleep(1);
if(pthread_rwlock_rdlock(&rwlock)!=0)
{
printf("writer is writing\n");
}
printf("read value:%d\n",value);
pthread_rwlock_unlock(&rwlock);
}
return (void*)0;
}
int main()
{
pthread_t tid1;
pthread_t tid2;
pthread_rwlock_init(&rwlock,NULL);
pthread_create(&tid1,NULL,writer,NULL);
pthread_create(&tid2,NULL,reader,NULL);
pthread_rwlock_destroy(&rwlock);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
运行结果: