113-python-多线程( 锁 )
# 互斥锁
"""
# 牺牲效率保证数据安全
# 出现两把或两把以上的锁,会出现 死锁
"""
from threading import Thread,Lock def fn(lock): global n lock.acquire() num = n n = num - 1 lock.release() n = 10 l = Lock() lis = [] for i in range(10): t = Thread(target=fn,args=(l,)) lis.append(t) t.start() for i in lis: i.join() print(n)
# 递归锁
"""
# 在同一个线程中拿多少把钥匙都可以
# 但是在不同的线程中,只能有一个线程拿到钥匙
"""
from threading import RLock fork_lock = noodle_lock = RLock() def eat1(name): noodle_lock.acquire() print('%s拿到1'%name) fork_lock.acquire() print('%s拿到1+'%name) print('%s: 1+1'%name) fork_lock.release() noodle_lock.release() def eat2(name): fork_lock.acquire() print('%s拿到2'%name) noodle_lock.acquire() print('%s拿到2+'%name) print('%s2+2'%name) noodle_lock.release() fork_lock.release() Thread(target=eat1,args=('q',)).start() Thread(target=eat1,args=('w',)).start() Thread(target=eat2,args=('e',)).start() Thread(target=eat2,args=('r',)).start()