Dining philosophers, starvation example in C POSIX THREADS

In the last post I implemented dining philosophers problem with deadlock. Let's try to fix it by adding one asymmetric philosopher. This one picks up as first right chopstick instead of left.

The change is simple:
    
    p4_t->nr = 4;
    p4_t->left = 0;
    p4_t->right = 4;
Yeah finally we don't have deadlocks in our multithread enterprise software :)
But wait! One philosopher becomes fatter and fatter, when others are very slim...Im not good at jokes.

It's happening because of unfair access. No one picks up chopstick of the asymmetric philosoper in the first try. "Starvation is a problem encountered in concurrent computing where a process is perpetually denied necessary resources to process its work." - Wikipedia

Now we must face the starvation problem.

4 pick up's right chopstick, happy bastard, EAT 
4 pick up's left chopstick 
4 pick up's right chopstick, happy bastard, EAT 
4 pick up's left chopstick 
4 pick up's right chopstick, happy bastard, EAT 
4 pick up's left chopstick 
4 pick up's right chopstick, happy bastard, EAT 
4 pick up's left chopstick 
4 pick up's right chopstick, happy bastard, EAT 


The situation is better when we add more asymmetric philosophers:
    p0_t->nr = 0;
    p0_t->left = 1;
    p0_t->right = 0;

    p1_t->nr = 1;
    p1_t->left = 1;
    p1_t->right = 2;

    p2_t->nr = 2;
    p2_t->left = 3;
    p2_t->right = 2;

    p3_t->nr = 3;
    p3_t->left = 3;
    p3_t->right = 4;

    p4_t->nr = 4;
    p4_t->left = 4;
    p4_t->right = 0;
4 pick up's right chopstick, happy bastard, EAT 
1 pick up's right chopstick, happy bastard, EAT 
2 pick up's left chopstick 
2 pick up's right chopstick, happy bastard, EAT 
But the behavior is unpredictable.
Full code here: https://github.com/khipis/c-unix-sandbox/blob/master/philosophers/philosophers_starvation.c

Komentarze

Popularne posty