Python--day37--进程锁
进程锁的示意图:
锁.py:
1 #锁 2 #火车票 3 import json 4 import time 5 6 from multiprocessing import Process 7 from multiprocessing import Lock 8 9 def show(i): 10 with open('ticket') as f: 11 dic = json.load(f) 12 print('余票:%s'%dic['ticket']) 13 14 def buy_ticket(i,lock): 15 lock.acquire() #拿钥匙进门 16 with open('ticket') as f: 17 dic = json.load(f) 18 time.sleep(0.1) 19 if dic['ticket'] > 0: 20 dic['ticket'] -= 1 21 print('\033[32m%s买到票了\033[0m'%i) 22 else: 23 print('\033[31m%s没买到票\033[0m'%i) 24 time.sleep(0.1) 25 with open('ticket','w') as f: 26 json.dump(dic,f) 27 lock.release() #还钥匙 28 29 if __name__ == '__main__': 30 for i in range(10): 31 p = Process(target=show, args=(i,)) 32 p.start() 33 lock = Lock() 34 for i in range(10): 35 p = Process(target=buy_ticket, args=(i,lock)) 36 p.start()
运行结果: