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()