from multiprocessing import Process, Lock import json import time def read_fares(pop): with open("file", "r") as f: num = json.loads(f.read())["count"] print("%d号获取到还剩%d张票" % (pop, num)) def get_fares(pop): with open("file", "r") as f: num = json.loads(f.read())["count"] time.sleep(0.1) #模拟读数据的网络延迟 if num > 0: num -= 1 time.sleep(0.2) #模拟写数据的网络延迟 with open("file", "w") as f: f.write(json.dumps({"count": num})) print("%d号买到票了" % pop) def task(pop,lock): read_fares(pop) lock.acquire() get_fares(pop) lock.release() if __name__ == "__main__": lock = Lock() for i in range(10): #开启十个进程共同抢票 p = Process(target=task, args=(i, lock)) p.start()
避免多个进程同时修改文件数据,所以加入进程锁。