线程锁模拟抢票系统
from multiprocessing import Process,Lock import json,random,time,os def search(): #查票 with open("db.txt",encoding='utf-8') as f: dic=json.load(f) print("%s 剩余票数 %s" %(os.getpid(),dic['count'])) def get(): #抢票 with open("db.txt",encoding='utf-8') as read_f: dic = json.load(read_f) if dic['count'] > 0: dic['count'] -=1 time.sleep(random.randint(1,3)) #模拟手速+网速 with open("db.txt",'w', encoding='utf-8') as write_f: json.dump(dic,write_f) print("\033[43;1m%s抢票成功\033[0m "%os.getpid()) def task(lock): search() #查找可能是并发执行, lock.acquire() #抢票才要锁,这也是用join的另一个不同 get() lock.release() if __name__ == "__main__": lock = Lock() for i in range(20): p = Process(target=task,args=(lock,)) p.start() #锁和join都是把并发变为串行,但是锁比join灵活,lock能让局部串行,而lock只能让全局串行