互斥锁
互斥锁:同一个资源不能由多个程序同时使用
由并发变成了串行
from multiprocessing import Process,Lock import time def task(name,mutex): mutex.acquire() print("%s 1" % name) time.sleep(1) print("%s 2" % name) time.sleep(1) print("%s 3" % name) time.sleep(1) mutex.release() if __name__ == "__main__": mutex=Lock()#所有进程必须使用同一把锁 for i in range(3): p=Process(target=task,args=("进程%s" % i,mutex)) p.start()
练习题:
模拟抢票软件
from multiprocessing import Process,Lock import json,time def search(name): time.sleep(2) dict=json.load(open("db.txt","r",encoding="utf-8")) print("%s 查看到剩余票数[%s]" % (name,dict.get("count",""))) def get(name,mutex): mutex.acquire() time.sleep(2) dict = json.load(open("db.txt", "r", encoding="utf-8")) if dict.get("count",0) >0: dict["count"]-=1 time.sleep(1) json.dump(dict,open("db.txt","w",encoding="utf-8")) print("%s 购票成功" % name) mutex.release() def task(name,mutex): search(name) get(name,mutex) if __name__=="__main__": mutex=Lock() for i in range(10): p=Process(target=task,args=(i,mutex)) p.start()