mirror of
https://github.com/Manoj-HV30/sp-lab.git
synced 2026-05-16 19:35:27 +00:00
81 lines
2.0 KiB
C
81 lines
2.0 KiB
C
#include<stdio.h>
|
|
#include<fcntl.h>
|
|
#include<semaphore.h>
|
|
|
|
int main(){
|
|
int n, phil, ch;
|
|
printf("Enter number of philosophers: ");
|
|
scanf("%d", &n);
|
|
|
|
int eating[n];
|
|
for(int i =0;i<n;i++)
|
|
eating[i]=0;
|
|
sem_t *chopstick[n];
|
|
char name[20];
|
|
|
|
for(int i=0;i<n;i++){
|
|
sprintf(name, "/c%d",i);
|
|
sem_unlink(name);
|
|
chopstick[i] = sem_open(name, O_CREAT, 0644, 1);
|
|
}
|
|
sem_unlink("/room");
|
|
sem_t *room = sem_open("/room", O_CREAT, 0644, n-1);
|
|
|
|
while(1){
|
|
printf("---\nDIning philosopher problem----\n");
|
|
printf("\n1.Pick chopstick(eat)");
|
|
printf("\n2.Put chopstick(think)");
|
|
printf("\n3.Exit");
|
|
printf("\nENter your choice: ");
|
|
scanf("%d", &ch);
|
|
|
|
if(ch==1){
|
|
printf("\nEnter the philosopher number (0 to %d): ", n-1);
|
|
scanf("%d",&phil);
|
|
|
|
if(eating[phil]){
|
|
printf("\nprofessor already eating");
|
|
continue;
|
|
}
|
|
sem_wait(room);
|
|
sem_wait(chopstick[phil]);
|
|
sem_wait(chopstick[(phil+1)%n]);
|
|
eating[phil] = 1;
|
|
printf("\nprofessor %d eating", phil);
|
|
}
|
|
else if(ch ==2){
|
|
printf("\nEnter the philosopher number (0 to %d): ",n-1);
|
|
scanf("%d", &phil);
|
|
|
|
if(!eating[phil]){
|
|
printf("\nphilosopher not eating");
|
|
continue;
|
|
}
|
|
sem_post(chopstick[phil]);
|
|
sem_post(chopstick[(phil+1)%n]);
|
|
sem_post(room);
|
|
eating[phil] = 0;
|
|
|
|
printf("Philosopher %d finished eating\n",
|
|
phil);
|
|
}
|
|
else if (ch == 3) {
|
|
break;
|
|
}
|
|
|
|
else {
|
|
printf("Invalid choice\n");
|
|
}
|
|
|
|
}
|
|
|
|
for(int i =0;i<n;i++){
|
|
sprintf(name, "/c%d", i);
|
|
sem_close(chopstick[i]);
|
|
sem_unlink(name);
|
|
}
|
|
sem_close(room);
|
|
sem_unlink("/room");
|
|
return 0;
|
|
}
|