Python单行桥实现中的死锁

2024-04-25 07:57:01 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图了解更多关于如何在python中使用信号量进行同步的知识。我有一个设置,我觉得应该工作,但我一直陷入僵局。这是典型的单车道桥梁问题,任何数量的汽车都可以行驶,只要它们朝同一方向行驶。我不担心挨饿,我知道如果有无限的水流从一个方向来,那么另一个方向就会饿死。我只想让这个信号灯工作。我强烈地认为这应该是有效的,也许这是一个python的东西?我觉得,如果资源(网桥)不可用,但它似乎不能正常工作,那么获取信号量应该是阻塞的。提前感谢您的任何意见!在

class OneLaneBridge(object):
"""
A one-lane bridge allows multiple cars to pass in either direction, but at any
point in time, all cars on the bridge must be going in the same direction.

Cars wishing to cross should call the cross function, once they have crossed
they should call finished()
"""

def __init__(self):
    self.dir = -1
    self.bridge_access = Semaphore()
    self.cars_on_bridge = 0
    self.mutex = Semaphore()


def cross(self,direction):
    """wait for permission to cross the bridge.  direction should be either
    north (0) or south (1)."""

    self.mutex.acquire()
    if(self.dir == -1): #direction has been reset
        self.dir = direction

    if(direction == self.dir): #cars already going this direction
        if(self.cars_on_bridge == 0): #first car in this direction acquires lock
            self.bridge_access.acquire()
        #there's now another car on the bridge
        self.cars_on_bridge += 1
    else:
        #block the car and add it to waiting queue (this is how semaphores work?)
        self.bridge_access.acquire()

    self.mutex.release()

def finished(self,direction):
   self.mutex.acquire()
   self.cars_on_bridge -= 1 #car is now off the bridge
   if(self.cars_on_bridge == 0): #no more cars on bridge so release access
       self.bridge_access.release()
       self.dir = -1 #reset the direction so the next car will dictate the direction

   self.mutex.release()

编辑:

正如正确指出的,问题出在cross()方法中。问题是互斥体没有被释放导致死锁,一旦互斥体被释放,汽车不再被封锁,它们就不能像其他车一样得到正确的处理。以下是新的cross方法,其中大部分更改都在else块中:

^{pr2}$

Tags: thetoinselfifaccessondir
1条回答
网友
1楼 · 发布于 2024-04-25 07:57:01

当错误方向的汽车在cross中阻塞时,它仍将保持互斥锁,因此其他线程在试图获取互斥锁时将死锁。在

同样,一旦一辆驶向错误方向的汽车在cross中解锁,它仍然没有开始过马路。你仍然需要设置方向并增加桥上车辆的数量,因为你只在汽车朝正确方向行驶时才这样做。如果您只是释放互斥体并像代码试图做的那样返回,cross的调用者将假定汽车已被允许上桥。在

相关问题 更多 >