线程锁实例2---读写加锁实例

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
struct student
{
	int a ; 
	int b ; 
	int c ; 
	int d ; 
	int e ; 
	int f ;
};

char stu[6] = {10,10,10,10,10,10};


//初始化一个线程mutex锁  主要用途是防止资源访问竞争
pthread_mutex_t   Mutex = PTHREAD_MUTEX_INITIALIZER ; 

int  write_stu(int value , const char *name);
void read_stu(void);

void *do_thread(void *arg);

int main(void)
{
	pthread_t  tid ; 
//	struct student stu = {10,20};
	int ret ; 
	ret = pthread_create(&tid , NULL , do_thread , (void *)100);
//	ret = pthread_create(&tid , NULL , do_thread , (void *)(&stu));
	if(ret < 0)
	{
		perror("create thread fail");
		return -1 ; 
	}
	
	ret = pthread_detach(tid);
	
	sleep(2);

	write_stu(80 , "main thread");


	return 0 ; 
}
void *do_thread(void *arg)
{
	//写数据函数
	//写数据的时候加把锁,为了防止读和写同时进行
	write_stu(50 , "thread");
	//读数据函数
	read_stu();
}
	
int  write_stu(int value , const char *name)
{
	//总共操作时间用6秒
	int i ; 
	//给一个线程上锁
	//上锁,这时候只写
	pthread_mutex_lock(&Mutex);
	for(i = 0 ; i < 6 ; i++)
	{
		stu[i] = value ; 
		printf("%s write value:%d \n" , name , value);
		sleep(1);
	}
	//写完了,解锁
	pthread_mutex_unlock(&Mutex);
}

//读数据
void read_stu(void)
{
	int i ; 
	for(i = 0 ; i < 6 ; i++)
	{
		printf("stu[%d] : %d \n" , i , stu[i]);
	}
}	

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值