以下是使用信号量变量解决仅可承重一人的独木桥问题的示例代码(使用Python语言):

from threading import Semaphore, Thread

class Bridge:
    def __init__(self):
        self.mutex = Semaphore(1)  # 控制桥的访问权限
        self.bridge = Semaphore(1)  # 控制桥的承重能力
        self.num_crossing = 0  # 记录当前过桥人数

    def cross_bridge(self, person):
        self.mutex.acquire()
        self.num_crossing += 1
        if self.num_crossing == 1:
            self.bridge.acquire()
        self.mutex.release()

        # 过桥操作
        print(f'{person} 正在过桥...')

        self.mutex.acquire()
        self.num_crossing -= 1
        if self.num_crossing == 0:
            self.bridge.release()
        self.mutex.release()

def person_thread(person, bridge):
    bridge.cross_bridge(person)

if __name__ == '__main__':
    bridge = Bridge()

    # 创建多个过桥的人
    persons = ['Person A', 'Person B', 'Person C', 'Person D']
    threads = []
    for person in persons:
        t = Thread(target=person_thread, args=(person, bridge))
        threads.append(t)
        t.start()

    # 等待所有线程结束
    for t in threads:
        t.join()

运行以上代码,将会模拟多个人依次过桥的情况,保证每次只有一个人在桥上。

用信号量解决独木桥问题:Python 代码示例

原文地址: https://www.cveoy.top/t/topic/fADm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录