#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
#define MAX_SIZE 20
#define BUFFER_SIZE 8
struct
{
pthread_mutex_t mutex;
pthread_cond_t nofull;
pthread_cond_t noempty;
int buff[BUFFER_SIZE];
int nput; //下标
int nval; //值
int count; //统计生产者存入的数的个数
}shared ={PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER};
void* produce(void *arg)
{
for(;;)
{
pthread_mutex_lock(&shared.mutex);
if(shared.nval >= 20)
{
pthread_mutex_unlock(&shared.mutex);
printf("produce finish.\n");
break;
}
if(shared.count < BUFFER_SIZE) //8
{
shared.buff[shared.nput] = shared.nval;
printf("shared.nput =%d\n",shared.nput);
shared.nput++; //下标+1
if(shared.nput >= BUFFER_SIZE)
{
shared.nput = 0;
}
shared.nval++ ; //为了方便,假设设置的值是对应的下标
shared.count++; //计数++
pthread_cond_signal(&shared.noempty);
}
else
pthread_cond_wait(&shared.nofull, &shared.mutex); //
pthread_mutex_unlock(&shared.mutex);
}
}
void* consume(void *arg)
{
int j = 0;
for(int i=0; i<MAX_SIZE;) //20
{
pthread_mutex_lock(&shared.mutex);
if(shared.count > 0)
{
i++;
printf("value = %d\n", shared.buff[j]);
j++;
if(j >= BUFFER_SIZE)
j = 0;
shared.count--;
pthread_cond_signal(&shared.nofull);
}
else
pthread_cond_wait(&shared.noempty, &shared.mutex);
pthread_mutex_unlock(&shared.mutex);
}
}
int main()
{
pthread_t ptid;
pthread_t ctid;
pthread_create(&ptid, NULL, produce, NULL);
pthread_create(&ctid, NULL, consume, NULL);
pthread_join(ptid,NULL);
pthread_join(ctid,NULL);
return 0;
}