I was creating a thread for a philosopher. Here is the pseudocode:

while(true)
  think
  get left chopstick
  get right chopstick
  eat
  putdown left chopstick
  putdown right chopstick

Intuitive, i don't think the order of relieving the chopstick will matter. So instad of putting down the left chopstick first, can i put the right chopstick down first? will this cause any error? I doubt it will. If this causes a deadlock, how? if not, but left first is recommended, then why?

Thank you!

有帮助吗?

解决方案

You have several locks here:

while(true)
  think

  wait until you finished thinking

  get left chopstick
  get right chopstick

  wait until you you took both sticks

  eat
  putdown left chopstick
  putdown right chopstick

The things between locks (waits) can success in any order because it does not matter.

其他提示

Imagine it visually. Say you have four philosophers and each has a chopstick between them.

All four grab their left chopsticks at once. This is okay, as everyone has a chopstick and nobody is competing for one.

Then they look to the right, there are no chopsticks left, because everyone has one of the four.

They can't eat, so they get deadlocked.

If you code it so after some time they give up and put down their chopsticks, you come across the same problem, as everyone tries to pick up the left chopstick and there are no right chopsticks left (timing can cause this to not happen, but it is better to code for it).

Instead, you should pick a philosopher, and have him pick up his right chopstick first. This breaks the deadlock, as either the right-chopstick philosopher or the philosopher to his left will succeed in getting both chopsticks and being able to eat (which will circle around and feed everyone eventually).

while(true)
  think

  identify nearest chopstick set location

  think

  get nearest chopstick of set
  get remaining chopstick of set

  eat

  putdown left chopstick
  putdown right chopstick
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top