0

I am implementing the dining philosopher problem in c using semaphores. My code works although i am confused as to why no deadlock is occurring at all.

CODE:

#include<stdio.h>
#include <semaphore.h> 
#include <pthread.h>
#include <unistd.h> 

sem_t cs[5];
pthread_t phils[5];
void pickup(int i){


    int k = (i+1)%5;
        printf("%d: HUNGRY %d %d \n",i+1,i,k);
        sem_wait(&cs[i]);
        sem_wait(&cs[k]); 
}

void putdown(int i){
    sem_post(&cs[i]);
    sem_post(&cs[(i+1) % 5]);    
    printf("%d: THINK \n",i+1);
}

void eat(int i){
    printf("%d: EAT\n",i+1);
}

void phil(void *i){
    while(1){
        usleep((rand()% 100000) + 100000);
        int n= *(int*)i;
        pickup(n);
        eat(n);
        putdown(n); 

    }
}


int main(){
    int id[5];
    while(1){
        for(int i = 0; i<5;i++){
              sem_init(&cs[i], 0, 1);
              id[i]=i;
              pthread_create (&phils[i], NULL, (void *) &phil, (void *) &id[i]);
        }

        sleep(100);
    }   

}

Chunk of OUTPUT:

2: HUNGRY 1 2 
2: EAT
2: THINK 
4: HUNGRY 3 4 
4: EAT
4: THINK 
5: HUNGRY 4 0 
5: EAT
5: THINK 
1: HUNGRY 0 1 
1: EAT
1: THINK 
3: HUNGRY 2 3 
3: EAT
3: THINK 
5: HUNGRY 4 0 
5: EAT
5: THINK 
4: HUNGRY 3 4 
4: EAT
4: THINK 
2: HUNGRY 1 2 
2: EAT
2: THINK 
1: HUNGRY 0 1 
1: EAT
1: THINK 
3: HUNGRY 2 3 
3: EAT
3: THINK 
2: HUNGRY 1 2 
2: EAT
2: THINK 
5: HUNGRY 4 0 
5: EAT
5: THINK 
4: HUNGRY 3 4 
4: EAT
4: THINK 
1: HUNGRY 0 1 
1: EAT
1: THINK 
2: HUNGRY 1 2 
2: EAT
2: THINK 
3: HUNGRY 2 3 
3: EAT
3: THINK 
4: HUNGRY 3 4 
4: EAT
4: THINK 
1: HUNGRY 0 1 
1: EAT
1: THINK 
5: HUNGRY 4 0 
5: EAT
5: THINK 
2: HUNGRY 1 2 
2: EAT
2: THINK 
3: HUNGRY 2 3 
3: EAT
3: THINK 
4: HUNGRY 3 4 
4: EAT
4: THINK 
1: HUNGRY 0 1 
1: EAT
1: THINK 
5: HUNGRY 4 0 
5: EAT
5: THINK 

I know this is a good thing but it seems like my threads are executing one after the other rather than concurrently, which defeats the point of threads.

Thanks in advance!

xSooDx
  • 493
  • 1
  • 5
  • 19
  • 2
    Deadlock occurs when each philosopher is holding `cs[i]` but is unable to get `cs[k]`. So put a `sleep` between the two `sem_wait` calls and it should deadlock. – user3386109 Sep 19 '16 at 07:08
  • 2
    Your philosophers spend a lot of time sleeping (0.1 seconds is an eternity to a modern computer). The probability of deadlock is reduced, since it is quite unlikely that two (adjacent) philosophers will even be awake at the same time. – EOF Sep 19 '16 at 16:12

0 Answers0