#include <myhead.h>
int Orange=0;
int Apple=0;
pthread_cond_t condition_apple;
pthread_cond_t condition_orange;
pthread_mutex_t mutex;
void* eat_5_apple_task(void* arg){
while(1){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condition_apple,&mutex);
Apple-=5;
printf("1号消费5个苹果,剩余苹果数:%d\n",Apple);
pthread_mutex_unlock(&mutex);
}
};
void* eat_7_orange_task(void* arg){
while(1){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condition_orange,&mutex);
Orange-=7;
printf("1号消费7个橘子,剩余橘子数:%d\n",Orange);
pthread_mutex_unlock(&mutex);
}
};
int main(int argc, const char *argv[])
{
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&condition_apple,NULL);
pthread_cond_init(&condition_orange,NULL);
pthread_t eat_5_apple_task_id;
pthread_t eat_7_orange_task_id;
pthread_create(&eat_5_apple_task_id,NULL,eat_5_apple_task,NULL);
pthread_create(&eat_7_orange_task_id,NULL,eat_7_orange_task,NULL);
while(1){
int num=rand();
pthread_mutex_lock(&mutex);
if(num%2==0){
Apple+=2;
}else{
Orange+=3;
}
printf("Apple:%d,\tOrange:%d\n",Apple,Orange);
if(Apple>5){
pthread_cond_signal(&condition_apple);
}
if(Orange>7){
pthread_cond_signal(&condition_orange);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
return 0;
}