简体   繁体   中英

Dining Philosophers in C memory leaks

i am trying to implement Dining Philosophers in C using Resource hierarchy solution. when i am using valgrind everything goes fine. Unfortunately when i done this using console im getting random seqfaults. One time my program will be succesful,one time it will broke on the beginning. I would be grateful if anybody could point where i did mistake and why it's 100% succesfull.

#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;
}
int i;

...

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

Passing a pointer to a local variable isn't going to work. You're passing the same address to all of the threads, so there's an inherent race condition. You point them a pointer to i and them almost immediately you increment i . What value will they read when they access *param ? Who knows!

You'll want to create an array with NUM_PHILOSPHERS (sic) slots in it and pass a different address to each thread. You'll also want to make sure that array isn't destroyed when main() exits—ie, make the array global or static, not local.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM