一个交易场所:有存储区域来保存数据
两种角色:读者、写者
三种关系:
- 读者与读者:没有关系
- 写者与写者:互斥(不能同时操作)
- 写者与读者:同步互斥(同步是写者优先)
相较于生产者消费者模型,读者间不互斥,提高效率
示例:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//定义读写锁
pthread_rwlock_t lock;
//定义交易场所
int g_count=0;
//读者线程
void* Reader(void *arg)
{
(void*)arg;
while(1)
{
pthread_rwlock_rdlock(&lock);
printf("count=%d\n",g_count);
pthread_rwlock_unlock(&lock);
Sleep(1);
}
return NULL;
}
//写者线程
void* Writer(void *arg)
{
(void*)arg;
int count=0;
while(1)
{
pthread_rwlock_wrlock(&lock);
++count;
g_count=count;
pthread_rwlock_unlock(&lock);
Sleep(1);
}
return NULL;
}
int main()
{
pthread_ewlock_init(&lock,NULL);//初始化读写锁
pthread_t tid1,tid2,tid3;
//创建线程
pthread_create(&tid1,NULL,Reader,NULL);
pthread_create(&tid3,NULL,Reader,NULL);
pthread_create(&tid2,NULL,Writer,NULL);
//线程等待
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_rwlock_destory(&lock);//销毁读写锁
system("pause");
return 0;
}