c - Resolving dining philosophers deadlock using semaphores -
i trying solve dining philosophers problem using semaphores in c. below code. in code each chopstick represented semaphore. each philosopher process. use concept atmost 4 chopsticks can in "picked up" state @ given time avoid deadlock. why set dt 4. please let me if below code correct , if logic sound
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sched.h> #include <signal.h> #include <sys/wait.h> #include <time.h> #include <semaphore.h> #define stacksize 10000 #define numprocs 5 #define rounds 10 sem_t dt,c1,c2,c3,c4,c5; int child (void * philnum) { int* phil1 = (int *)philnum; int phil = *phil1; int = 0 ; ( ; < rounds ; ++ ) { switch(phil){ case 1: sem_wait(&dt); sem_wait(&c1); sem_wait(&c5); case 2: sem_wait(&dt); sem_wait(&c1); sem_wait(&c2); case 3: sem_wait(&dt); sem_wait(&c3); sem_wait(&c2); case 4: sem_wait(&dt); sem_wait(&c4); sem_wait(&c3); case 5: sem_wait(&dt); sem_wait(&c4); sem_wait(&c5); default: perror(null); exit(1); } // start of critical section -- int sleeptime = rand()%20000 ; if ( sleeptime > 10000 ) usleep(sleeptime) ; // exit protocol here switch(phil){ case 1: sem_post(&dt); sem_post(&c1); sem_post(&c5); case 2: sem_post(&dt); sem_post(&c1); sem_post(&c2); case 3: sem_post(&dt); sem_post(&c3); sem_post(&c2); case 4: sem_post(&dt); sem_post(&c4); sem_post(&c3); case 5: sem_post(&dt); sem_post(&c4); sem_post(&c5); default: perror(null); exit(1); } } return 0 ; } int main ( int argc, char ** argv ) { int i, num ; int *pt= (int *)malloc(sizeof(int)); void * p ; srand(time(null)); sem_init(&c1,1,1); sem_init(&c2,1,1); sem_init(&c3,1,1); sem_init(&c4,1,1); sem_init(&c5,1,1); sem_init(&dt,1,4); //only 4 chopsticks can picked @ time. 5th 1 has wait anyways cant eat 1 chopstick ( = 0 ; < numprocs ; ++ ) { p = malloc(stacksize) ; if ( p == null ) { printf("error allocating memory\n") ; exit(1) ; } *pt = i+1; int c = clone(child,p+stacksize-1,clone_vm|sigchld,(void *)pt,null) ; if ( c < 0 ) { perror(null) ; exit(1) ; } } ( ; > 0 ; -- ) wait(null) ; return 0 ; }
your cases falling through.
Comments
Post a Comment