#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<string.h>
#include<time.h>
#define BUFFERSIZE 5
struct msg
{
time_t timep;
int id;
int pidid;
};
int in;
int out;
int count=0;
int m;
sem_t sem;
struct msg stack[BUFFERSIZE+1],nextP,nextC;
int ran_time()
{
int j;
j=1+(int)(5.0*rand()/(RAND_MAX+1.0));
return j;
}
void producer(void)
{
int i=0;
while(i<10)
{
sleep(ran_time());
while((in+1)%BUFFERSIZE==out);
sem_wait(&sem);
time(&nextP.timep);
nextP.id=i;
nextP.pidid=pthread_self();
stack[in]=nextP;
in=(in+1)%BUFFERSIZE;
count++;
++i;
sem_post(&sem);
}
}
void customer(void)
{
int m=0;
while(m<10)
{
sleep(ran_time());
while(in==out);
sem_wait(&sem);
nextC.timep=stack[out].timep;
nextC.id=stack[out].id;
nextC.pidid=stack[out].pidid;
out=(out+1)%BUFFERSIZE;
count--;
++m;
printf("customer:customer_pid: %d ;time:%s ; id: %d ; pidid: %d count:%d\n",pthread_self(),ctime(&nextC.timep),nextC.id,nextC.pidid,count);
sem_post(&sem);
}
}
int main(void)
{
pthread_t t1,t2,t3,t4;
pthread_attr_t attr;
sem_init(&sem,0,1);
pthread_attr_init(&attr);
pthread_create(&t1,&attr,(void*)producer,NULL);
pthread_create(&t2,&attr,(void*)customer,NULL);
pthread_create(&t3,&attr,(void*)producer,NULL);
pthread_create(&t4,&attr,(void*)customer,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
pthread_join(t4,NULL);
}