Dining philosophers, counting semaphore solution, C POSIX THREADS Example

One of the solution in dining philosopher problem is to set up counting semaphore, which eliminates the phenomenon of deadlock, because only 4 philosophers at a time can compete for the chopsticks, so it will eliminate a situation that all philosophers will raise at once left chopstick.
sem_t sem;

void *philosopher_semaphore(void *p) {
    struct philosopher_t philosopher = *((struct philosopher_t *) (p));
    while (1) {
        sem_wait(&sem); // Semaphore up
        if (!pthread_mutex_lock(&chopstick[philosopher.left])) {
            printf("%d pick up's left chopstick \n", philosopher.nr);
            while (1) {
                if (!pthread_mutex_lock(&chopstick[philosopher.right])) {
                    printf("%d pick up's right chopstick, happy bastard, EAT \n", philosopher.nr);
                    pthread_mutex_unlock(&chopstick[philosopher.left]);
                    pthread_mutex_unlock(&chopstick[philosopher.right]);
                    break;
                }
            }
        }
        sem_post(&sem); //Semaphore down
    }
}

int main() {

    sem_init(&sem, 0, 4); //Initialization of semaphore counting to 4
...
Now we have the real concurrency:
1 pick up's right chopstick, happy bastard, EAT 
1 pick up's left chopstick 
1 pick up's right chopstick, happy bastard, EAT 
1 pick up's left chopstick 
1 pick up's right chopstick, happy bastard, EAT 
2 pick up's left chopstick 
2 pick up's right chopstick, happy bastard, EAT 
3 pick up's left chopstick 
3 pick up's right chopstick, happy bastard, EAT 
2 pick up's left chopstick 
2 pick up's right chopstick, happy bastard, EAT 
0 pick up's left chopstick 
0 pick up's right chopstick, happy bastard, EAT 
Happy coding!
Full code here: https://github.com/khipis/c-unix-sandbox/blob/master/philosophers/philosophers_semaphore.c

Komentarze

Popularne posty