• python 多线程笔记(4)-- 车站售票模拟


    import threading
    import time
    import random
    
    class Worker(threading.Thread):
        '''售票员'''
        def __init__(self, wait_num=5, index=0):
            super().__init__()
            self.wait_num = wait_num          # 当前排队人数
            self.setName('窗口' + str(index)) # 窗口号
     
        def run(self):
            global counter, mutex
            
            while counter and self.wait_num: # 若有余票且有人排队
                # ============================
                # 窗口问询
                # ============================
                time.sleep(random.randrange(2,10)) # 比较耗时,时间随机
                
                # ============================
                # 出票
                # ============================
                mutex.acquire()         # 锁住①
                if counter == 0:        # 如果票数为0
                    mutex.release()     # 解锁③ -----> 这句很重要!!!
                    print(self.getName(), ':抱歉,票已售完')
                    break
                    
                counter = counter - 1   # 票数减一
                print('{}:当前余票 {} 张'.format(self.getName(), counter))
                mutex.release()         # 解锁③
                
                # ============================
                # 排队人数变化
                # ============================
                self.wait_num -= 1                      # 排队人数减一
                self.wait_num += random.randrange(0,2)  # 排队人数随机增加
    
        
    if __name__ == '__main__':
        # 剩余车票数
        counter = 20
        
        # 创建锁
        mutex = threading.Lock()
        
        # 开4个售票窗口
        workers = []
        for i in range(4):
            wait_num = random.randrange(2,10) # 窗口前排队人数随机
            workers.append(Worker(wait_num, i+1)) 
        
        # 开始售票
        for w in workers:
            w.start()
        
        # 阻塞主程/后台静默?自己选
        #for w in workers:
        #    w.join()
  • 相关阅读:
    ROSS仿真系统简单教程
    python小练习1.1
    c语言文件I/O 文件读取和写入
    Python 学习笔记 多线程-threading
    parsec(The parsec benchmark suit )使用教程
    Checkpoint/Restore In Userspace(CRIU)使用细节
    Checkpoint/Restore in Userspace(CRIU)安装和使用
    考研总结
    北理计算机复试经验
    PAT(A) 1075. PAT Judge (25)
  • 原文地址:https://www.cnblogs.com/hhh5460/p/5178683.html
Copyright © 2020-2023  润新知