代码:
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define Max 100
pthread_mutex_t mutex;
pthread_cond_t conditional_m;
int global=0;
void *thread_1_exe(void *flag){
while(global<Max){
pthread_mutex_lock(&mutex);
if(global%8==0) pthread_cond_signal(&conditional_m);//unlock mutex
else printf("In thread 1 global=%d\n",global);
pthread_mutex_unlock(&mutex);
sleep(1);
global++;
}
}
void *thread_2_exe(void *flag){
while(global<Max){
pthread_mutex_lock(&mutex);
if(global%8!=0)
pthread_cond_wait(&conditional_m,&mutex);
else
printf("Thread 2:global=%4d\n",global);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(void){
pthread_t thread_1;
pthread_t thread_2;
int error1,error2;
pthread_mutex_init(&mutex,NULL);//mutex type:default
pthread_cond_init(&conditional_m,NULL);
error1=pthread_create(&thread_1,NULL,thread_1_exe,(void *)NULL);
error2=pthread_create(&thread_2,NULL,thread_2_exe,(void *)NULL);
if(error1!=0||error2!=0){
printf("thread create error\n ");
}
pthread_join(thread_2,NULL);//NULL:message from pthread_exit()
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&conditional_m);
getchar();
return 1;
}