Python解决操作系统习题中PV操作过桥问题

 

上图是一道操作系统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()
    

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值