4,5 04 互斥锁 抢票程序
# 互斥锁/进程锁/同步锁 # import json import time from multiprocessing import Process,Lock def show_t(i): with open('ticket','r',encoding='utf-8') as f: ticket_data = f.read() # print(ticket_data) t_data = eval(ticket_data) # print(t_data,type(t_data)) print('%s查询剩余票数为%s'%(i,t_data['count'])) def get_t(i,l1): l1.acquire() with open('ticket', 'r', encoding='utf-8') as f: ticket_data = f.read() # print(ticket_data) t_data = eval(ticket_data) # print(t_data,type(t_data)) # print('%s查询剩余票数为%s' % (i, t_data['count'])) if t_data['count'] > 0: t_data['count'] -= 1 print('%s抢票成功'%i) time.sleep(0.2) with open('ticket', 'w') as f: f.write(str(t_data)) else: print('没票了!!!') l1.release() if __name__ == '__main__': l1 = Lock() for i in range(10): p1 = Process(target=show_t,args=(i,)) p1.start() for i in range(10): p2 = Process(target=get_t,args=(i,l1) ) p2.start() # import time # # def f1(i,lic): # lic.acquire() # time.sleep(1) # print(i) # lic.release() # # if __name__ == '__main__': # lic = Lock() # for i in range(20): # p = Process(target=f1, args=(i,lic)) # p.start()