互斥锁 (进程)
-
-
from multiprocessing import Process import time def son1(): while True: time.sleep(0.1) print('in son1') def son2(): for i in range(10): print('in son2') if __name__ == '__main__': ret=Process(target=son1) ret.daemon=True #表示ret是一个守护进程,必须现在start上面 ret.start() ret2=Process(target=son2) ret2.start() time.sleep(2) ret2.join() #等待ret2结束之后守护进程在结束 print('结束')
-
互斥锁
-
涉及多进程之间数据安全的问题,使用锁确保每次只有一个用户对数据经行修改
-
def func(i,lock): lock.acquire() #拿钥匙 print(f'被锁起来的代码{i}') time.sleep(1) lock.release() #还钥匙 if __name__ == '__main__': lock = Lock() for i in range(10): ret = Process(target=func,args=(i,lock)) ret.start()
-
购票:在并发的情况下,确保数据的安全性
def search(i): #搜索票 # count={'count':4} # with open('time1',mode='a',encoding='utf-8')as f: #写入数据 # json.dump(count,f) with open('time1',encoding='utf-8')as f: p=json.load(f) print(f"当前的票数是{p['count']}张!") def buy_tivket(i): #修改票 with open('time1',encoding='utf-8')as f: p=json.load(f) if p['count']>0: p['count']-=1 print(f'{i}购票成功!') time.sleep(1) with open('time1',mode='w',encoding='utf-8')as f: json.dump(p,f) #方式一 def get_ticket(i,lock): #获取票 search(i) #搜索 lock.acquire() #拿钥匙 buy_tivket(i) #对这和函数里面的代码进行了上锁 lock.release() # 还钥匙 #方式二 方式二比较好with会自动进行拿钥匙和还钥匙,并再次基础上做了一些异常处理,保证即便一个进程的代码出错也会归还钥匙 #def get_ticket(i,lock): #获取票 # search(i) #搜索 # with lock: # buy_tivket(i) if __name__ == '__main__': lock=Lock() for i in range(10): ret=Process(target=get_ticket,args=(i,lock)) ret.start()
-