
When I solved the philosopher dining problem, I encountered a deadlock situation. After the program has been running for a period of time, the program is in a state where n philosophers (n threads) have each acquired a chopstick. At this time, all philosophers want to get a second chopstick to eat, but share resources N chopsticks have been held by n philosophers, the chopsticks that each other wants are in the hands of other philosophers, and there is no mechanism to make any philosopher give up the chopsticks held in his hands, thus causing all philosophers ( All threads) are waiting for the deadlock problem of resources in the hands of others.
- Mutual Exclusion: 1 chopstick can only be used by one philosopher.
- Hold and Wait: When a philosopher wants other chopsticks, he will not put down the chopsticks he has already obtained.
- No Preemption: the chopsticks that the philosopher has obtained are putting down Previously, they would not be deprived
- Circular Waiting : philosophers formed a head-to-tail circular waiting for resources relationship.
Solution:
In order to prevent the deadlock from happening, two conditions can be set:
- you must pick up the left and right chopsticks at the same time;
- eating is allowed only when neither neighbor has a meal.