# Author:Winter Liu is coming! import time from multiprocessing import Process, Lock import json def search(i): with open("ticket_data", mode="r", encoding="utf-8") as f: ticket = json.load(f) print("{},票有{}张".format(i, ticket["count"])) def buy_ticket(i, lock): # 锁定,中间部分代码唯一执行 lock.acquire() with open("ticket_data", mode="r", encoding="utf-8") as f: ticket = json.load(f) if ticket["count"] > 0: ticket["count"] -= 1 print("{}.购票成功!".format(i)) time.sleep(0.2) with open("ticket_data", mode="w", encoding="utf-8") as f: json.dump(ticket, f) # 解锁 lock.release() if __name__ == "__main__": # 主进程创建 锁 lock = Lock() for i in range(10): p = Process(target=buy_ticket, args=(i+1, lock)) p.start()
修改后:
# Author:Winter Liu is coming! import time from multiprocessing import Process, Lock import json def ticket_search(i): with open("ticket_data", mode="r", encoding="utf-8") as f: ticket = json.load(f) print("{},票有{}张".format(i, ticket["count"])) def buy_ticket(i): with open("ticket_data", mode="r", encoding="utf-8") as f: ticket = json.load(f) if ticket["count"] > 0: ticket["count"] -= 1 print("{}.购票成功!".format(i)) time.sleep(0.2) with open("ticket_data", mode="w", encoding="utf-8") as f: json.dump(ticket, f) def get_tiket(i,lock): ticket_search(i) lock.acquire() buy_ticket(i) lock.release() if __name__ == "__main__": # 主进程创建 锁 lock = Lock() for i in range(10): p = Process(target=get_tiket, args=(i+1, lock)) p.start()