python_并发编程——锁
多进程模拟买票~
import time import json from multiprocessing import Process class Show(Process): #查 def run(self): with open(‘ticket‘) as f: dic = json.load(f) print("余票:{}".format(dic[‘ticket‘])) class Buy_ticket(Process): #买 def __init__(self,name): super().__init__() self.name = name def run(self): with open(‘ticket‘) as f: dic = json.load(f) time.sleep(0.1) #模拟网络延迟 if dic[‘ticket‘] > 0: dic[‘ticket‘] -=1 print(‘{}买到票了~~~‘.format(self.name)) time.sleep(0.1) #模拟网络延迟 with open(‘ticket‘,‘w‘) as f: json.dump(dic,f) else: print(‘{}没买到票!!!‘.format(self.name)) if __name__ == ‘__main__‘: for i in range(10): q1 = Show() q1.start() for i in range(10): i = str(i) q2 = Buy_ticket(i) q2.start()
json文件:结果:余票为1却有两个人买到票了~。
加上锁之后
import time import json from multiprocessing import Process from multiprocessing import Lock class Show(Process): #查 def run(self): with open(‘ticket‘) as f: dic = json.load(f) print("余票:{}".format(dic[‘ticket‘])) class Buy_ticket(Process): #买 def __init__(self,name,lock): #接收锁对象 super().__init__() self.name = name self.lock = lock def run(self): self.lock.acquire() #拿钥匙进门 with open(‘ticket‘) as f: dic = json.load(f) time.sleep(0.1) #模拟网络延迟 if dic[‘ticket‘] > 0: dic[‘ticket‘] -=1 print(‘{}买到票了~~~‘.format(self.name)) time.sleep(0.1) #模拟网络延迟 with open(‘ticket‘,‘w‘) as f: json.dump(dic,f) else: print(‘{}没买到票!!!‘.format(self.name)) self.lock.release() #还钥匙 if __name__ == ‘__main__‘: for i in range(10): q1 = Show() q1.start() lock = Lock() #定义一个锁对象 for i in range(10): i = str(i) q2 = Buy_ticket(i,lock) #将锁对象传入子进程 q2.start()
json文件:结果:就只有三个人买到了~~
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16