from multiprocessing import Process,Lock
import json
import os
import time
import random
mutex=Lock()
def check():
with open('db.json','rt',encoding='utf-8') as f:
dic=json.load(f)
print('%s 剩余票数:%s' %(os.getpid(),dic['count']))
def get():
with open('db.json','rt',encoding='utf-8') as f:
dic=json.load(f)
time.sleep(1)
if dic['count'] > 0:
dic['count']-=1
time.sleep(random.randint(1,3)) #模拟网络延迟
with open('db.json','wt',encoding='utf-8') as f:
json.dump(dic,f)
print('%s 抢票成功' %os.getpid())
def task(mutex):
# 并发查看
check()
# 串行购票
mutex.acquire()
get()
mutex.release()
if __name__ == '__main__':
for i in range(10):
p=Process(target=task,args=(mutex,))
p.start()
# p.join() # 将p内的代码变成整体串行
执行结果如下:
2464 剩余票数:1
2256 剩余票数:1
5832 剩余票数:1
6008 剩余票数:1
2788 剩余票数:1
4292 剩余票数:1
5252 剩余票数:1
2448 剩余票数:1
5880 剩余票数:1
5940 剩余票数:1
2464 抢票成功