python 哲学家进餐问题

import threading


class DiningPhilosophers:
    def __init__(self):
        self.cv = threading.Condition()
        
        # 字典对象,表示每个哲学家0,1,2,3,4的状态,False表示未吃饭
        self.d = {}
        for i in range(5):
            self.d[i] = False
	
	# actions表示多函数指针
    def wantsToEat(self, philosopher: int, *actions) -> None:、
  		# 获取邻居的下标0,1,2,3,4
        neighbors = [philosopher - 1, philosopher + 1]
        if neighbors[0] < 0: neighbors[0] = 4
        if neighbors[1] > 4: neighbors[1] = 0
		
        with self.cv:
          	# 判断邻居是否都是未吃饭
            self.cv.wait_for(lambda: not self.d[neighbors[0]] and not self.d[neighbors[1]])
            # True表示正在吃饭
            self.d[philosopher] = True
			
			# 将多函数指针通过map函数映射成可执行的函数,即指针---》指针()
			# 因为map函数返回的是map对象,所以这里进行强制数据类型转换,来使actions正常执行
            list(map(lambda x: x(), actions))

        self.d[philosopher] = False

你可能感兴趣的:(python 哲学家进餐问题)