读者写者模型【设计模型】

一个交易场所:有存储区域来保存数据
两种角色:读者、写者
三种关系

  • 读者与读者:没有关系
  • 写者与写者:互斥(不能同时操作)
  • 写者与读者:同步互斥(同步是写者优先)

相较于生产者消费者模型,读者间不互斥,提高效率

示例:

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值