#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#define n 10
typedef sem_t semaphore;
semaphore s;
semaphore full;
semaphore empty;
int in = 0;
int out = 0;
int buffer[n] = {0};
int max_items = 10;
int produce_item()
{
}
void insert_item(int item)
{
buffer[in] = item;
in = (in+1)%n;
}
int remove_item()
{
int item = buffer[out];
out = (out+1)%n;
return item;
}
void* producer(void* arg)
{
for(int i=0;i<max_items;i++)
{
int item = produce_item();
sem_wait(&empty);
sem_wait(&s);
insert_item(item);
printf("Produced item : %d\n",item
); sem_post(&full);
sem_post(&s);
}
}
void* consumer(void* arg)
{
for(int i=0;i<max_items;i++)
{
sem_wait(&full);
sem_wait(&s);
int item = remove_item();
printf("Consumed item : %d\n",item
); sem_post(&s);
sem_post(&empty);
}
}
int main()
{
pthread_t pro,con;
sem_init(&s,0,1);
sem_init(&full,0,0);
sem_init(&empty,0,n);
pthread_create(&pro,NULL,producer,NULL);
pthread_create(&con,NULL,consumer,NULL);
pthread_join(pro,NULL);
pthread_join(con,NULL);
sem_destroy(&s);
sem_destroy(&full);
sem_destroy(&empty);
return 0;
}
I2luY2x1ZGU8c3RkaW8uaD4KI2luY2x1ZGU8c3RkbGliLmg+CiNpbmNsdWRlPHB0aHJlYWQuaD4KI2luY2x1ZGU8c2VtYXBob3JlLmg+CgojZGVmaW5lIG4gMTAKCnR5cGVkZWYgc2VtX3Qgc2VtYXBob3JlOwpzZW1hcGhvcmUgczsKc2VtYXBob3JlIGZ1bGw7CnNlbWFwaG9yZSBlbXB0eTsKaW50IGluID0gMDsKaW50IG91dCA9IDA7CmludCBidWZmZXJbbl0gPSB7MH07CmludCBtYXhfaXRlbXMgPSAxMDsKCmludCBwcm9kdWNlX2l0ZW0oKQp7CglyZXR1cm4gcmFuZCgpJTEwMDsKfQoKdm9pZCBpbnNlcnRfaXRlbShpbnQgaXRlbSkKewoJYnVmZmVyW2luXSA9IGl0ZW07CglpbiA9IChpbisxKSVuOwp9CgppbnQgcmVtb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