我正在尝试仅使用信号量/互斥量来实现单向桥,单向桥有三个规则:
这是规则4的图表
(字母代表汽车,破折号代表桥梁)
B is alreaydy on the road:
-----B-------
A arrives, waits for B:
A---B--------
A--B---------
now C arrives, same direction as B, and waits for B and A since A arrived first.
A-B---------C
AB----------C
B exits, A takes over
-A----------C
...
-----------AC
Finally A exits and C takes over
-----------C-
现在我有一个互斥锁,当它上面有车时会锁定桥,但是我不能让规则4发生。任何更明智的想法将不胜感激!
答案 0 :(得分:0)
当汽车接近桥梁时,它会获得递增令牌。当两辆车在对面等待桥梁自由时,具有较小令牌的车辆优先。这应解决你的#4。
// initial conditions
bridge.calling = 1
bridge.next_ticket = 0
// car approaching the bridge
bridge.mutex.lock();
myself.ticket = ++ bridge.next_ticket
while (bridge.calling != myself.ticket)
bridge.condition.wait(bridge.lock)
bridge.mutex.unlock()
// drive through the bridge
bridge.mutex.lock()
++ bridge.calling
bridge.mutex.unlock()
bridge.condition.notify_all()