1.互斥锁
import time from threading import Thread,Lock def func1(lock): global n lock.acquire() #加锁 temp = n time.sleep(0.2) n = temp -1 lock.release() #解锁 n = 10 t_list = [] lock = Lock() for i in range(10): t1 = Thread(target=func1,args=(lock,)) t1.start() t_list.append(t1) for i in t_list: i.join() print(n)
结果: 牺牲了执行的速度,但保证了数据的安全性。
2.递归锁
from threading import Thread,RLock def func1(name): lock1.acquire() print('{}拿到第一把钥匙!'.format(name)) lock2.acquire() print('{}拿到第二把钥匙!'.format(name)) print('{}进入了房间'.format(name)) lock2.release() #归还第二把钥匙 lock1.release() #归还第一把钥匙 lock1 = RLock() #锁1 lock2 = RLock() #锁2 for i in range(10): Thread(target=func1,args=(i,)).start()
结果: 当同时需要拿到两把钥匙才可以执行代码时,容易出现分别两个不同的线程,每个线程各拿到一把钥匙时,就会出现死锁,所有递归锁就可以解决这样的问题。