学习锁机制
l = LOCK()
一把锁配一把钥匙
拿钥匙,锁门,l.acquire()
还钥匙,开门,i.release()
from multiprocessing import Lock l = Lock() l.acquire()# 拿走钥匙,锁门,不让其他人进屋 l.release()# 释放锁。 还钥匙,开门,允许其他人进屋
例子:
from multiprocessing import Process,Value,Lock import time def get_money(num,l):# 取钱 l.acquire()# 拿走钥匙,锁上门,不允许其他人进屋 for i in range(100): num.value -= 1 print(num.value) time.sleep(0.01) l.release()# 还钥匙,打开门,允许其他人进屋 def put_money(num,l):# 存钱 l.acquire() for i in range(100): num.value += 1 print(num.value) time.sleep(0.01) l.release() if __name__ == '__main__': num = Value('i',100) l = Lock() p = Process(target=get_money,args=(num,l)) p.start() p1 = Process(target=put_money, args=(num,l)) p1.start() p.join() p1.join() print(num.value)
from multiprocessing import Process, Lock import json, time def rob_tickets (i, l): time.sleep(1) l.acquire() # 拿钥匙 with open('file', 'r') as f: last_tickets_info = json.load(f) last_tickets = last_tickets_info['count'] if last_tickets > 0: last_tickets = last_tickets - 1 last_tickets_info['count'] = last_tickets with open('file', 'w') as f: json.dump(last_tickets_info, f) print('