(单车道桥问题)允许多辆车同时通过

时间:2021-02-21 15:58:41

标签: python python-3.x multithreading concurrency queue

我希望有多个线程使用相同的资源。

我正在研究 Single lane bridge problem 的变体,其中最多三辆车可以同时过桥,只要它们按照进入桥的顺序离开桥,并且只要所有车辆都通过朝着同一个方向行驶。

在我的版本中,我希望最多 n 个线程可以访问公共资源。

而且我希望这些线程中的每一个都以类似 FIFO 的方式以正确的顺序完成计算。

有没有办法添加一个大小为 Queuen 来代表桥梁, 然后加起来 n 个踏板?

到目前为止,这是我的工作代码。

现在的样子,左边的车先过桥,然后右边的。

from threading import Lock, Thread, Semaphore
import logging
import time


class ThreadsProcessing:

    def __init__(self):
        # Threads list.
        self.threads = []
        # Lock objects.
        self.lock_enter_bridge = Lock()
        self.lock_exit_bridge = Lock()
        self.bridge_sem = Semaphore(0)


    def left_side_car(self):
        print('Car from left side is starting ...')
        print('Car from left is waiting to acquire permission to enter bridge.')
        self.lock_enter_bridge.acquire()
        print('Car from left has acquired permission to enter bridge, crossing bridge...')
        time.sleep(2)
        print('Car from left is waiting to acquire lock to exit bridge.')
        self.lock_exit_bridge.acquire()
        print('Car from left has acquired lock to exit bridge')
        print('Car from left has exited the bridge and will release both locks.')
        self.lock_enter_bridge.release()
        self.lock_exit_bridge.release()
        print("Car from left tells the semaphore to the bridge semaphore that its finished with crossing the bridge")
        self.bridge_sem.release()



    def right_side_car(self):
        logging.info('Car from right side is starting ...')
        logging.info('Car from right is waiting to acquire permission to enter bridge.')
        # Two workers, wait for both of them
        numOfWorkers = 2
        for _ in range(numOfWorkers):
            print('Waiting for bridge semaphore...')
            self.bridge_sem.acquire()
            print("Car from right got the bridge semaphore")
        logging.info("Car from right is crossing the bridge...")
        time.sleep(4)
        print("Car from right has finished crossing the bridge all done")
        self.bridge_sem.release()

    def start_car_threads(self):
        for thread_func in [self.left_side_car, self.right_side_car]:
            self.threads.append(Thread(target=thread_func))
            self.threads[-1].start()

    def join_threads(self):
        for thread in self.threads:
            thread.join()


if __name__ == '__main__':
    car_threads = ThreadsProcessing()
    car_threads.start_car_threads()
    car_threads.join_threads()
    logging.info('Finished')

问题的完整描述是这样的: 单车道桥最多可支撑三辆朝同一方向行驶的汽车。提供无饥饿的实现。

i) 每辆车开始向桥的左边缘(L)或右边缘(R)移动,这取决于汽车的方向值

ii)每辆车需要一个随机时间 t_arrive 过桥。

iii)当汽车到达桥的左(L)或右(R)边缘时,必要的过程将使用必要的参数调用方法到达桥

bridge-crossing-schematic

0 个答案:

没有答案