多进程下车票购买导致的数据冲突问题
'''
JSON文件 tick_data内容:{"tick_num": 0}
'''
import random import time from multiprocessing import Process import json def search_ticket(name): with open(r'ticket_data', mode='rt', encoding='utf-8') as f: ticket_dic = json.load(f) print(f'用户{name}查询车票剩余{ticket_dic.get("tick_num")}') def buy_ticket(name): with open(r'ticket_data', mode='r', encoding='utf-8') as f: ticket_dic = json.load(f) # 模拟网络延迟 time.sleep(random.randint(1, 3)) if ticket_dic.get("tick_num") > 0: ticket_dic['tick_num'] -= 1 with open(r'ticket_data', mode='w', encoding='utf-8') as f: json.dump(ticket_dic, f) print(f'用户{name}购票成功!') else: print(f'用户{name}购票失败!') def task(name): search_ticket(name) buy_ticket(name) if __name__ == "__main__": for i in range(1, 11): p = Process(target=task, args=(i,)) p.start()
通过Lock() 类加锁解决数据冲突问题
import random import time from multiprocessing import Process,Lock import json
def search_ticket(name): with open(r'ticket_data', mode='rt', encoding='utf-8') as f: ticket_dic = json.load(f) print(f'用户{name}查询车票剩余{ticket_dic.get("tick_num")}') def buy_ticket(name,mutex): with open(r'ticket_data', mode='r', encoding='utf-8') as f: ticket_dic = json.load(f) # 模拟网络延迟 time.sleep(random.randint(1, 3)) if ticket_dic.get("tick_num") > 0: ticket_dic['tick_num'] -= 1 with open(r'ticket_data', mode='w', encoding='utf-8') as f: json.dump(ticket_dic, f) print(f'用户{name}购票成功!') else: print(f'用户{name}购票失败!') def task(name,mutex): search_ticket(name) #查票不需要锁,买票时需要用锁控制顺序保证数据安全 #抢锁 mutex.acquire() buy_ticket(name,mutex) #释放锁 mutex.release() if __name__ == "__main__": mutex = Lock() for i in range(1, 11): p = Process(target=task, args=(i,mutex)) p.start()
标签:__,name,python,dic,互斥,json,进程,import,ticket From: https://www.cnblogs.com/palx/p/17204606.html