Files
sp-lab/3.c
T
2026-05-14 00:24:19 +05:30

55 lines
1.0 KiB
C

#include<stdio.h>
#include<semaphore.h>
#include<fcntl.h>
int main(){
int read_count = 0;
int data= 0;
sem_unlink("/mutex"); sem_unlink("/wrt");
sem_t *mutex = sem_open("/mutex", O_CREAT, 0644, 1);
sem_t *wrt = sem_open("/wrt", O_CREAT, 0644, 1);
int choice;
while(1){
printf("\n1.Read");
printf("\n2.Write");
printf("\n3.exit");
printf("\nEnter the choice: ");
scanf("%d", &choice);
if(choice ==1){
sem_wait(mutex);
read_count++;
if(read_count==1)
sem_wait(wrt);
sem_post(mutex);
printf("read data: %d | Active readers: %d", data, read_count);
sem_wait(mutex);
read_count--;
if(read_count==0)
sem_post(wrt);
sem_post(mutex);
}
else if(choice ==2){
sem_wait(wrt);
data+=10;
printf("wrote data: %d", data);
sem_post(wrt);
}else{
break;
}
}
sem_close(mutex);
sem_close(wrt);
sem_unlink("/mutex");
sem_unlink("/wrt");
return 0;
}