Files
2026-05-14 00:24:19 +05:30

71 lines
1.6 KiB
C

#include<stdio.h>
#include<fcntl.h>
#include<semaphore.h>
int main(){
int n;
printf("\nENter buffer size: ");
scanf("%d", &n);
int buffer[n];
int in =0, out= 0;
sem_unlink("/mutex");
sem_unlink("/empty");
sem_unlink("/full");
sem_t *mutex = sem_open("/mutex", O_CREAT, 0644, 1);
sem_t *empty = sem_open("/empty", O_CREAT, 0644, n);
sem_t *full = sem_open("/full", O_CREAT, 0644, 0);
int ch, item;
while(1){
printf("\n--- Producer Consumer ---");
printf("\n1. Produce (Write)");
printf("\n2. Consume (Read)");
printf("\n3. Exit");
printf("\nEnter choice: ");
scanf("%d", &ch);
if(ch==1){
printf("\nEnter item to write: ");
scanf("%d", &item);
sem_wait(empty);
sem_wait(mutex);
buffer[in]= item;
printf("\nProduced: %d at buffer[%d]", item, in);
in = (in+1)%n;
sem_post(mutex);
sem_post(full);
}
else if(ch==2){
sem_wait(full);
sem_wait(mutex);
item = buffer[out];
printf("\nconsumed: %d at buffer[%d]", item, out);
out = (out+1)%n;
sem_post(mutex);
sem_post(empty);
}
else if (ch == 3) {
break;
}
else {
printf("Invalid choice\n");
}
}
sem_close(mutex); sem_close(full); sem_close(empty);
sem_unlink("/mutex");
sem_unlink("/empty");
sem_unlink("/full");
return 0;
}