pthread_mutex_t mutex;
pthread_cond_t cond;
int apple = 0;
void* run1(void* arg){
while(1){
if(apple < 4){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
}
apple -= 4;
printf("1#线程消费了4个苹果,现在苹果数量为:%d\n",apple);
sleep(2);
pthread_mutex_unlock(&mutex);
}
}
void* run2(void* arg){
while(1){
if(apple < 7){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
}
apple -= 7;
printf("2#线程消费了7个苹果,现在苹果数量为:%d\n",apple);
sleep(3);
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, const char *argv[])
{
pthread_cond_init(&cond,0);
pthread_mutex_init(&mutex,0);
pthread_t id1;
pthread_t id2;
if(pthread_create(&id1,0,run1,0)!=0){
perror("pthread_create_1");
return 1;
}
if(pthread_create(&id2,0,run2,0)!=0){
perror("pthread_create_2");
return 2;
}
pthread_detach(id1);
pthread_detach(id2);
while(1){
apple += 3;
if(apple >= 7){
pthread_cond_signal(&cond);
}
printf("生产了3个苹果,现在苹果数量为:%d\n",apple);
sleep(1);
}
return 0;
}
生产者模型极简版
最新推荐文章于 2024-11-15 22:25:12 发布