#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int g_data = 0;
pthread_mutex_t mutex;
void *func1(void *arg){
printf("t1:%ld thread is created\n",(unsigned long)pthread_self());
printf("t1:param is %d\n",*((int *)arg));
pthread_mutex_lock(&mutex); //把线程锁住
while(1){
printf("t1: %d\n\n",g_data++);
sleep(1);
if(g_data ==3){
printf("t1=3 quit ======================\n");
pthread_mutex_unlock(&mutex); //知道g_data等于3时解锁线程
pthread_exit(NULL);
}
}
}
void *func2(void *arg){
printf("t2:%ld thread is created\n",(unsigned long)pthread_self());
printf("t2:param is %d\n",*((int *)arg));
while(1){
printf("t2: %d\n",g_data);
pthread_mutex_lock(&mutex); //进入while后线程被t1锁住
g_data++;
pthread_mutex_unlock(&mutex); //解锁线程
sleep(1);
}
}
int main()
{
int ret;
pthread_t t1;
pthread_t t2;
int param = 100;
pthread_mutex_init(&mutex, NULL);
ret = pthread_create(&t1,NULL,func1,(void *)¶m);
if(ret == 0){
printf("main:create t1 success \n");
}
ret = pthread_create(&t2,NULL,func2,(void *)¶m);
if(ret == 0){
printf("main:create t1 success \n");
}
printf("main :%ld\n",(unsigned long)pthread_self());
while(1){
printf("main :%d\n",g_data++);
sleep(1);
}
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}