餐饮哲学家的无阻塞解决方案

Seb*_*Seb 6 python algorithm blocking dining-philosopher

我被要求为python中的餐饮哲学家问题写一个简单的解决方案.这本身似乎很直接但是有些困惑,因为我被要求编写一个非阻塞解决方案.在这种情况下,我不确定这是什么意思.

有人能够提供任何提示或指出我正确的方向吗?

kra*_*ich 4

以下是非阻塞算法的定义: 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)
Run Code Online (Sandbox Code Playgroud)

该解决方案使用比较和交换习惯用法。