linux系统编程:线程同步-读写锁(rwlock)

                              线程同步-读写锁(rwlock)

读写锁

读写锁是互斥量的细化:显然,只有对全局资然进行写入操作时,才需要同步;在对全局资然进行读取操作时,是不需要锁的。


相关函数

pthread_rwlock_t    //读写锁类型
pthread_rwlock_init //初始化
pthread_rwlock_destroy  //销毁锁
pthread_rwlock_rdlock   //获取读锁
pthread_rwlock_wrlock   //获取写锁
pthread_rwlock_tryrdlock
pthread_rwlock_trywrlock
pthread_rwlock_unlock   //释放读写锁
    

示例

#include 
#include 
#include 
pthread_rwlock_t rwlock;
int counter = 0;
void *fun_r(void *argv)
{
	while (1)
	{
		//既然是读操作,当然可以完全不用锁
		pthread_rwlock_rdlock(&rwlock);
		printf("thread %x read,counter=%d\n", pthread_self(), counter);
		pthread_rwlock_unlock(&rwlock);
		sleep(1);
	}
}
void *fun_w(void *argv)
{
	while (1)
	{
		//写操作,写操作使用写锁
		pthread_rwlock_wrlock(&rwlock);
		counter++;
		printf("thread %x write,counter=%d\n", pthread_self(), counter);
		pthread_rwlock_unlock(&rwlock);
		sleep(1);
	}
}
int main(void)
{
	pthread_rwlock_init(&rwlock, NULL);
	pthread_t tid[5];
	int i;
	//开启2个线程读
	for (i = 0; i < 2; i++)
	{
		pthread_create(&tid[i], NULL, fun_r, NULL);
	}
	//开启3个线程写
	for (i = 2; i < 5; i++)
	{
		pthread_create(&tid[i], NULL, fun_w, NULL);
	}
	for (i = 0; i < 5; i++)
	{
		pthread_join(tid[i], NULL);
	}
	pthread_rwlock_destroy(&rwlock);
	return 0;
}

        



CCPP Blog 目录

你可能感兴趣的:(linux系统编程)