有人要求我用 Python 写一个简单的解决哲学家就餐问题的方法。这本身看起来很简单,但有些令人困惑,因为我被要求编写一个非阻塞解决方案。我不确定在这种情况下这是什么意思。
有没有人能给我任何提示或指出正确的方向?
最佳答案
这里是一个非阻塞算法的定义:http://en.wikipedia.org/wiki/Non-blocking_algorithm .
这个问题的非阻塞解决方案的伪代码:
# The number of forks.
FORKS_COUNT = ...
# Indicates if the i-th fork is taken or not.
taken = new bool[FORKS_COUNT]
# The philosopherId is a position at the table.
def haveDinner(philosopherId):
leftFork = philosopherId
rightFork = (philosopherId + 1) % FORKS_COUNT
if leftFork > rightFork:
swap(leftFork, rightFork)
while true:
# Tries to take the left fork.
while not compare_and_swap(taken[leftFork], false, true):
# Do nothing.
# Tries to take the right fork.
while not compare_and_swap(taken[rightFork], false, true):
# Do nothing.
# Eats.
...
# Returns the forks to the table.
compare_and_swap(taken[leftFork], true, false)
compare_and_swap(taken[rigthFork], true, false)
此解决方案使用 compare-and-swap成语。
关于python - 用餐哲学家的非阻塞解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28549066/