互斥锁

在这里插入图片描述
在这里插入图片描述

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>

struct student {
int age ;
int name;
int id;

}stu;
//定义两个全局变量
int i=0;
pthread_mutex_t mutex;

void *thread_fun1(){
while(1)
{
    //加锁,对整个结构体访问进行加锁,防止产生错乱
	pthread_mutex_lock(&mutex);
stu.age=i;
stu.name=i;
stu.id=i;

if(stu.id!=stu.age||stu.id!=stu.name||stu.age!=stu.name){
printf("%d,%d,%d\n",stu.id,stu.age,stu.name);

break;
}
i++;
//访问变量完成,需要进行解锁,只有这样其他线程才能访问
pthread_mutex_unlock(&mutex);
}
}


void *thread_fun2(){
while(1)
{
	 pthread_mutex_lock(&mutex);
stu.age=i;
stu.name=i;
stu.id=i;



if(stu.id!=stu.age||stu.id!=stu.name||stu.age!=stu.name){
printf("%d,%d,%d\n",stu.id,stu.age,stu.name);

break;


}
i++;
pthread_mutex_unlock(&mutex);
}
}

int main(){

pthread_t tid1 ,tid2;
	int err;
//对互斥量进行初始化,只有初始化互斥量才能使用
	err=pthread_mutex_init(&mutex,NULL);

	if(err!=0){
		printf("init mutex fail\n");
	
	}
//创造新线程
	err=pthread_create(&tid1 ,NULL,thread_fun1,NULL);

	if(err!=0){
		printf("cxcw\n");
		return 0;
	
	}

	err=pthread_create(&tid2 ,NULL,thread_fun2,NULL);

        if(err!=0){
                printf("cxcw\n");
                return 0;

        }
//等待新线程运行结束
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);


return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值