Dining Philosophers on C memory leaks

I am trying to implement dining philosophers in C using a resource hierarchy solution. when i use valgrind everything goes well. Unfortunately when I did it using the console im getting random seqfaults. One day my program is successful, one time it breaks from the start. I would appreciate it if someone could point out where I went wrong and why it is 100% successful.

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

#define NUM_PHILOSPHERS 5

sem_t forks[NUM_PHILOSPHERS];
void *philosopher(void *param){
    printf("Thread created!");
    int *id = (int *)param;
    int L = 0;
    sem_t* Myforks[2];
    int par = *id;
    if(par == 4){
        Myforks[0]  = &forks[4];
        Myforks[1]  = &forks[0];
    }else{
        Myforks[0]  = &forks[par];
        Myforks[1]  = &forks[par+1];
    }
    while(L!=5){    
        printf("Eat spaghetti!",*id);
        sem_wait(Myforks[0]);
        sem_wait(Myforks[1]);
        //.....
        printf("EAT spaghetti!",*id);
        sem_post(Myforks[1]);
        sem_post(Myforks[0]);
        L=L+1;
    }
    pthread_exit(NULL);
}

int main(){
    int i;
    pthread_t threads[NUM_PHILOSPHERS];

    for(i = 0; i < NUM_PHILOSPHERS; i++)
        sem_init(&forks[i], 0, 1);
    for(i = 0; i < NUM_PHILOSPHERS; i++)
        pthread_create(&threads[i], NULL, philosopher, (void *)&i);
    return 0;
}

      

+3


source to share


1 answer


int i;

...

for(i = 0; i < NUM_PHILOSPHERS; i++) 
  pthread_create(&threads[i], NULL, philosopher, (void *)&i);
                                                         ^^

      

Passing a pointer to a local variable will not work. You are passing the same address to all threads, so there is an inherent race condition. You point a pointer to them i

, and you increase them almost immediately i

. What value will they read when they access *param

? Who knows!



You need to create an array with NUM_PHILOSPHERS

(sic) slots in it and pass a different address to each thread. You will also want to make sure the array is not destroyed when main()

exits-ie.Make the array global or static, not local.

+3


source







All Articles