题目 2 :
一座小桥(最多只能承重两个人)横跨南北两岸,
任意时刻同一方向只允许一人过桥,南侧桥段和北侧桥段
较窄只能通过一人,桥中央一处宽敞,允许两个人通过或
歇息。要求:
① 请用 PV 操作为同步机制写出它们能正确并发执行的伪代码;
② 请用你熟悉的线程库编程实现此并发程序,并模型桥两岸各 25 人过桥的情况。
答案在这=》
import threading
import time
from concurrent.futures import ThreadPoolExecutor
Empty = threading.Semaphore(16)
N = threading.Lock()
S = threading.Lock()
def NtoS(id):
Empty.acquire()
N.acquire()
print(id + "走在北桥!")
N.release()
S.acquire()
print(id + "走在南桥!")
S.release()
Empty.release()
def StoN(id):
Empty.acquire()
S.acquire()
print(id + "走在南桥!")
S.release()
N.acquire()
print(id + "走在北桥!")
N.release()
Empty.release()
if __name__ == "__main__":
Threading_Pool = ThreadPoolExecutor(max_workers=50)
for i in range(25):
Threading_Pool.submit(NtoS, "NtoS"+str(i))
for j in range(25):
Threading_Pool.submit(NtoS, "StoN"+str(j))