The content is from 《Foundations Of Qt Development》

The philosophers are getting ready to dine.

The algorithm used by the philosophers for eating is divided into five steps:

  1. Acquire the left chopstick.
  2. Acquire the right chopstick.
  3. Eat.
  4. Release the right chopstick.
  5. Release the left chopstick.

Because all philosophers are equally hungry, they all start at once by picking up the left chopstick. The problem is that one philosopher’s left chopstick is the right chopstick for another. So they all block when they try to acquire the right chopstick. A deadlock occurs, and they all starve to death.

Look for threads competing for more than one resource that also acquire these resources at different times. If each philosopher were to try to acquire both chopsticks in one operation, the problem would never occur.

Solution algorithm:

  1. Acquire the left chopstick.
  2. Try to acquire the right chopstick.
  3. If both sticks were acquired, continue to step 6.
  4. Release the left chopstick.
  5. Think for a while before continuing with step 1.
  6. Eat.
  7. Release the right chopstick.
  8. Release the left chopstick.

Categories: C plus plus

Leave a Reply

Your email address will not be published. Required fields are marked *