爲了保證數據的安全,所以要犧牲掉效率,效率慢json
#db.txt {"count": 2}
from multiprocessing import Process import json,time,os def search(): time.sleep(1)#模擬網絡信號IO with open('db.txt',mode='rt',encoding='utf8') as f: res = json.load(f) print(f'還剩餘{res["count"]}') def get(): with open('db.txt',mode='rt',encoding='utf8') as f: res = json.load(f) time.sleep(1) if res['count']>0: res['count']-=1 with open('db.txt',mode='wt',encoding='utf8') as f: json.dump(res,f) time.sleep(1.5) print(f'進程{os.getpid()}搶票成功') else: print('票已經售空啦!!!!!!!') def task(): search() get() if __name__ == '__main__': for i in range(15): p = Process(target=task) p.start() p.join() ###################### 還剩餘2 進程4904搶票成功 還剩餘1 進程16108搶票成功 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!! 還剩餘0 票已經售空啦!!!!!!!
from multiprocessing import Process,Lock import json, time, os def search(): time.sleep(1) # 模擬網絡io with open('db.txt', mode='rt', encoding='utf8') as f: res = json.load(f) print(f'還剩餘{res["count"]}') def get(): with open('db.txt', mode='rt', encoding='utf8') as f: res = json.load(f) time.sleep(1) if res['count'] > 0: res['count'] -= 1 with open('db.txt', mode='wt', encoding='utf8') as f: json.dump(res, f) time.sleep(1.5) print(f'{os.getpid()}搶票成功') else: print('票已經售空!!!!!!!!!!!!') def task(lock): search() #鎖住 lock.acquire() get() lock.release() if __name__ == '__main__': lock = Lock()#寫在主進程中是爲了讓子進程拿到同一把鎖 for i in range(15): p = Process(target=task,args=(lock,)) p.start() p.join() #進程鎖,是把鎖住的代碼變成串行 #jion是把全部的子進程變成串行 ####################### 還剩餘2 7964搶票成功 還剩餘1 11164搶票成功 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!! 還剩餘0 票已經售空!!!!!!!!!!!!
from multiprocessing import Process,Lock import json, time, os def search(): time.sleep(1) # 模擬網絡io with open('db.txt', mode='rt', encoding='utf8') as f: res = json.load(f) return res['count'] def get(): with open('db.txt', mode='rt', encoding='utf8') as f: res = json.load(f) print(f'還剩餘{res["count"]}') time.sleep(1) if res['count'] > 0: res['count'] -= 1 with open('db.txt', mode='wt', encoding='utf8') as f: json.dump(res, f) time.sleep(1.5) print(f'{os.getpid()}搶票成功') else: print('票已經售空!!!!!!!!!!!!') def task(lock): search() #鎖住 lock.acquire() get() lock.release() if __name__ == '__main__': lock = Lock()#寫在主進程中是爲了讓子進程拿到同一把鎖 for i in range(15): p = Process(target=task,args=(lock,)) p.start() p.join() #進程鎖,是把鎖住的代碼變成串行 #jion是把全部的子進程變成串行 res = search() if res==0: p.terminate() break ################# 還剩餘2 4356搶票成功 還剩餘1 15936搶票成功