读写锁例子

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

int counter;

pthread_rwlock_t rwlock;

void *th_write(void *arg);
void *th_read(void *arg);


int main(int argc, char *argv[])
{

	int i = 0;
	pthread_t tid[8];
	pthread_rwlock_init(&rwlock, NULL);
	//创建三个写线程
	for(i = 0; i<3; i++)
	{
		pthread_create(&tid[i], NULL, th_write, (void*)i);//不能&i 和 i = *((int*)arg)
	}
	//创建5个读线程
	for(i = 0; i<5; i++)
	{
		pthread_create(&tid[i+3], NULL, th_read, (void*)i);
	}
	for(i = 0; i < 8; i++)
	{
		pthread_join(tid[i], NULL);
	}
	pthread_rwlock_destroy(&rwlock);
}

void *th_write(void *arg)
{
	 int i = (int)arg;
	int t = 0;
	for( ; ; )
	{
		pthread_rwlock_wrlock(&rwlock);
		t = counter;
		usleep(1000);
		printf("write %d: %lu: counter = %d ++counter = %d\n", i, pthread_self(), t, ++counter);
		pthread_rwlock_unlock(&rwlock);
		usleep(10000);//这个延时大的目的是让读锁有机会进行读,不然一直让写锁独占
	}
	return NULL;
}

void *th_read(void *arg)
{
	 int i = (int)arg;
	for( ; ; )
	{
		pthread_rwlock_rdlock(&rwlock);
		printf("read %d: %lu: counter = %d\n", i ,pthread_self(), counter);
		pthread_rwlock_unlock(&rwlock);
		usleep(2000);
	}
	return NULL;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值