# 进程锁的代价是,失去异步效果
# db.txt文件内容:{"count": 1}
from multiprocessing import Process
from multiprocessing import Lock
import time
import json
def search():
time.sleep(1)
f = open('json.txt','r',encoding='utf-8')
ticket =json.load(f)
print(f"剩余票数:{ticket['count']}")
f.close()
return ticket
def buy():
ticket = search()
if ticket['count'] > 0:
ticket['count'] -=1
print('购买完成')
f = open('json.txt', 'w')
f.write(json.dumps(ticket))
def task(lock):
lock.acquire() # 上锁
buy()
lock.release() #解锁
if __name__ == '__main__':
lock = Lock()
for i in range(3):
p = Process(target=task,args=(lock,)) # 创建三个进程,每个进程都加锁,表示该进程完成后才能执行下个进程
p.start()
返回结果:
剩余票数:1
购买完成
剩余票数:0
剩余票数:0
python进程锁
于 2022-03-06 23:04:43 首次发布