a.zip点击(此处)折叠或打开
-
#include<stdio.h>
-
#include<pthread.h>
-
#include<stdlib.h>
-
#define MAX 1000
-
-
pthread_mutex_t mutex;
-
pthread_cond_t condc,condp;
-
-
int bread_num=0;
-
-
void *producer(void*argc)
-
{
-
while(1)
-
{
-
pthread_mutex_lock(&mutex);
-
-
if(bread_num==MAX)
-
{
-
printf("Sum of bread is full ! call consumer...\n");
-
sleep(1);
-
pthread_cond_wait(&condp,&mutex);
-
}
-
-
bread_num++;
-
printf("Producer: Bread+1 now sum is %d\n",bread_num);
-
usleep(5000);
-
pthread_cond_signal(&condc);
-
-
pthread_mutex_unlock(&mutex);
-
}
-
pthread_exit(0);
-
}
-
-
void *consumer(void*argc)
-
{
-
while(1)
-
{
-
pthread_mutex_lock(&mutex);
-
-
if(bread_num==0)
-
{
-
printf("Sum of bread is empty ! call produce...\n");
-
sleep(1);
-
pthread_cond_wait(&condc,&mutex);
-
}
-
bread_num--;
-
printf("Consumer: Bread-1 now sum is %d\n",bread_num);
-
usleep(5000);
-
pthread_cond_signal(&condp);
-
-
pthread_mutex_unlock(&mutex);
-
}
-
pthread_exit(0);
-
-
}
-
-
int main()
-
{
-
pthread_t pro,con;
-
-
pthread_mutex_init(&mutex,NULL);
-
pthread_cond_init(&condp,NULL);
-
pthread_cond_init(&condc,NULL);
-
-
pthread_create(&pro,NULL,producer,NULL);
-
pthread_create(&con,NULL,consumer,NULL);
-
-
pthread_join(pro,NULL);
-
pthread_join(con,NULL);
-
-
pthread_cond_destroy(&condp);
-
pthread_cond_destroy(&condc);
-
pthread_mutex_destroy(&mutex);
-
-
return 0;
- }