#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;
}