/*************************************************************************
> File Name: pro_res.c
> Author: qinf
> Mail:
> Created Time: Tue 01 Apr 2014 10:09:44 AM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
int pro_sum = 0;
int lef_sum = 20;
pthread_mutex_t mutex_pro, mutex_lef;
pthread_cond_t cond_pro, cond_lef;
void *thd1_handle(void *arg) {
while(1) {
pthread_mutex_lock(&mutex_pro);
if (pro_sum > 0) {
pthread_mutex_lock(&mutex_lef);
-- pro_sum;
if (pro_sum == 19) {
pthread_cond_signal(&cond_lef);
}
++lef_sum;
printf("thd1 consum 1, pro_sum= %d, pro_lef= %d\n", pro_sum, lef_sum);
pthread_mutex_unlock(&mutex_lef);
} else if (pro_sum == 0) {
pthread_cond_wait(&cond_pro, &mutex_pro);
}
pthread_mutex_unlock(&mutex_pro);
sleep(4);
}
}
void *thd2_handle(void *arg) {
while(1) {
pthread_mutex_lock(&mutex_pro);
if (pro_sum > 0) {
pthread_mutex_lock(&mutex_lef);
-- pro_sum;
if (pro_sum == 19) {
pthread_cond_signal(&cond_lef);
}
++lef_sum;
printf("thd2 consum 1, pro_sum= %d, pro_lef= %d\n", pro_sum, lef_sum);
pthread_mutex_unlock(&mutex_lef);
} else if (pro_sum == 0) {
pthread_cond_wait(&cond_pro, &mutex_pro);
}
pthread_mutex_unlock(&mutex_pro);
sleep(4);
}
}
int main() {
pthread_t thd1, thd2;
pthread_mutex_init(&mutex_pro, NULL);
pthread_mutex_init(&mutex_lef, NULL);
pthread_cond_init(&cond_pro, NULL);
pthread_cond_init(&cond_lef, NULL);
pthread_create(&thd2, NULL, thd2_handle, NULL);
pthread_create(&thd1, NULL, thd1_handle, NULL);
sleep(3);
while(1) {
pthread_mutex_lock(&mutex_lef);
if (lef_sum > 0) {
pthread_mutex_lock(&mutex_pro);
-- lef_sum;
++ pro_sum;
printf("main produce, pro_sum %d, lef_sum %d\n", pro_sum, lef_sum);
if (pro_sum == 1) {
pthread_cond_broadcast(&cond_pro);
}
pthread_mutex_unlock(&mutex_pro);
sleep(1);
}else if (lef_sum == 0) {
pthread_cond_wait(&cond_lef, &mutex_lef);
sleep(1);
}
pthread_mutex_unlock(&mutex_lef);
sleep(1);
}
return 0;
}
生产者消费者问题(实现)
最新推荐文章于 2021-08-23 12:12:15 发布