#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
// using namespace std;
const unsigned int N=30;
int buffer[30];
sem_t Empty;
sem_t full;
sem_t s;
int In=0;
int out=0;
void * producer(void *value)
{
int val=(int)value;
//int x = *((int*)(&arg));
while(val)
{
sem_wait(&Empty);
sem_wait(&s);
buffer[In]=val;
In=(In+1);
val--;
usleep(5);
sem_post(&s);
sem_post(&full);
}
return 0;
}
void * consumer(void *co){
int c=(int)co;
while(c)
{
sem_wait(&full);
sem_wait(&s);
int item=buffer[out];
out=(out+1);
// cout<<"consumed: "<<item<<endl;
printf("consumed: %dn" ,item
);
usleep(5);
c--;
sem_post(&s);
sem_post(&Empty);
}
return 0;
}
int main() {
sem_init(&Empty,0,N);
sem_init(&full,0,0);
sem_init(&s,0,1);
pthread_t cons;
pthread_t prod;
pthread_create(&cons,null,consumer,(void*)5);
pthread_create(&prod,null,producer,(void*)10);
pthread_join(cons,null);
pthread_join(prod,null);
return 0;
}