上图是一道操作系统PV操作的习题,用Python解决之,建立一个线程模拟行人从北向南过桥,另一个线程模拟行人从南向北过桥,建立四个信号量,分别实现对桥、北桥段、南桥段和桥中央的互斥。
north_side = threading.Semaphore(1) #北桥段只能通过一人
north= threading.Semaphore(1) #北向南一次只允许一人过桥
south_side = threading.Semaphore(1) #南桥段只能通过一人
south= threading.Semaphore(1) #南向北一次只允许一人过桥
person = threading.Semaphore(2) #桥中央允许两人通过或歇息
随机生成20个线程(行人),观察行人过桥的状况,符合题目要求,运行结果如下图。
import threading,time,random
north_side = threading.Semaphore(1)
north= threading.Semaphore(1)
south_side = threading.Semaphore(1)
south= threading.Semaphore(1)
person = threading.Semaphore(2)
def north_south():
t = threading.currentThread()
north_side.acquire()
north.acquire()
print('行人%dnorth_south上北桥段\n'%t.ident)
time.sleep(random.random())
north.release()
person.acquire()
print('行人%dnorth_south行至桥中央\n'%t.ident)
time.sleep(random.random())
person.release()
south.acquire()
print('行人%dnorth_south上至南桥段\n'%t.ident)
time.sleep(random.random())
south.release()
print('行人%dnorth_south下桥\n'%t.ident)
north_side.release()
def south_north():
t = threading.currentThread()
south_side.acquire()
south.acquire()
print('行人%dsouth_north上南桥段\n'%t.ident)
time.sleep(random.random())
south.release()
person.acquire()
print('行人%dsouth_north行至桥中央\n'%t.ident)
time.sleep(random.random())
person.release()
north.acquire()
print('行人%dsouth_north上至北桥段\n'%t.ident)
time.sleep(random.random())
north.release()
print('行人%dsouth_north下桥\n'%t.ident)
south_side.release()
if __name__=='__main__':
threads = []
for i in range(20):
r=random.randint(0,1)
if r==0:
p = threading.Thread(target=north_south)
else:
p = threading.Thread(target=south_north)
p.start()
threads.append(p)
for t in threads:
t.join()