标签:class tar roc with open 数据 时间 加锁 操作 search
互斥锁:模拟购票系统(join 可以实现串行运行程序,但是join的操作不够灵活)
数据文件 ‘db.json‘ 的格式为 {“count”: 1,...}
from multiprocessing import Process, Lock import json import time import random import os def search(): time.sleep(0.1) with open(‘db.json‘,‘r‘, encoding=‘utf-8‘) as f: dic = json.load(f) print(‘%s正在查票%s‘%(os.getpid(),dic[‘count‘])) return dic[‘count‘] def get(): with open(‘db.json‘, ‘r‘, encoding=‘utf-8‘) as f: dic = json.load(f) if dic[‘count‘] > 0: dic[‘count‘] -= 1 time.sleep(random.randint(1,3)) with open(‘db.json‘, ‘w‘, encoding=‘utf-8‘) as f: json.dump(dic, f) print(‘%s 购票成功‘%os.getpid()) def task(lock):
##lock.acquire() ###只能一个一个的查看余票数,但是这样做不合理。 search() ###并发查票 lock.acquire() ###大家可以共同查找网站余票,在同一时间看到的票数相同。 购票的时候抢锁 lock.acquire() get() ###查看完余票之后才能去购票,购票的过程模拟先到先得。不能同时多个人得到同一张余票 lock.release() ### # def task(): # search() # get() if __name__ == ‘__main__‘: lock = Lock() for i in range(10): p = Process(target=task, args= (lock,)) # p = Process(target=task) p.start()
标签:class tar roc with open 数据 时间 加锁 操作 search
原文地址:https://www.cnblogs.com/tina053/p/10333792.html