线程间同步互斥(2)读写锁使用

概念:允许多个读出,但只允许一个写入的需求。

读写锁与互斥量类似,不过读写锁允许更改的并行性,也叫共享互斥锁

互斥量要么是锁住状态,要么就是不加锁状态,而且一次只有一个线程可以对其加锁。
读写锁可以有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;
}

注意:读写锁适合于对数据结构的读次数比写次数多得多的情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值