python - 用餐哲学家的非阻塞解决方案

标签 python algorithm blocking dining-philosopher

有人要求我用 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/

相关文章:

iOS 如何迭代集合并获取每个项目的用户响应

python - 如何在我的主项目中添加 setuptools entry_point 作为示例?

python - Python 中断言失败

python - 从 url 不变的网站中抓取响应表

c++ - 在 C++ 中转换树

delphi - 创造 *。 Mht 文件(网络存档)

spring-boot - 高负载时 Spring react 性能差

python - keras model.get_weight 未返回预期尺寸的结果

c++ - 在 c++ 中的不同行或列旁边搜索最小值和最大值的最快方法是什么

algorithm - 给定一个数字链表。交换每 2 个相邻链接