#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> //互斥锁的头文件
void *func(); //线程函数声明
int count;
int num1=0;
int num2=0;
int num3=0;
pthread_mutex_t mutex1;//互斥锁声明
int main()
{
pthread_t thread1;//新建线程声明
int ret= pthread_mutex_init(&mutex1,NULL);//初始化一个互斥锁
if(ret<0)
{
perror("pthread_mutex_init");
exit(-1);
}
if(0!=pthread_create(&thread1,NULL,func,NULL))//线程函数使用
{
perror("pthread_create");
exit(-1);
}
while(1)
{
pthread_mutex_lock(&mutex1);//上锁
num1 = count;
num2 =count;
count++;
pthread_mutex_unlock(&mutex1);//解锁
}
return 0;
}
void *func()//线程函数
{
while(1)
{
pthread_mutex_lock(&mutex1);//上锁
if(num1!=num2)//不相等不打印
{
printf("num1 =%d,num2=%d\n",num1,num2);
}
if(num1==num2)//相等打印
printf("whhhhhhh");
pthread_mutex_unlock(&mutex1);//解锁
}
}