""" 抢票! 多个用户在同时读写同一个数据 """ from multiprocessing import Process,Lock import json,time,random # 查看余票 def show_ticket(name): time.sleep(random.randint(1,3)) with open(r"ticket.json","rt",encoding="utf-8") as f: dic = json.load(f) print("%s查看 剩余票数:%s" % (name ,dic["count"])) # 购买票 def buy_ticket(name): # 购买前再次查询 with open(r"ticket.json", "rt", encoding="utf-8") as f: # 修改数据 dic = json.load(f) if dic["count"] > 0: dic["count"] -= 1 # 模拟网络延迟 time.sleep(random.randint(1,3)) # 模拟服务器收到数据 写入文件 with open(r"ticket.json", "wt", encoding="utf-8") as f2: json.dump(dic,f2) print("%s 购票成功!" % name) def task(lock,name): # 查看余票可以并发执行 不需要锁住 show_ticket(name) # 购票的操作需要锁 因为设涉及到同时修改数据 lock.acquire() buy_ticket(name) lock.release() if __name__ == '__main__': # 买个锁 mutex = Lock() # 所有子进程 必须是同一把锁,否则无法实现——锁定的状态 for i in range(11): p = Process(target=task,args=(mutex,"客户%s" % i)) p.start() # 查询票这个事情 可以多个进程同时执行 # 但是买票这个过程 不能同时进行 前一个没买完 后一个就不能买