线程锁,

from threading import Thread,Lock

noodle_lock = Lock()
chazi_lock = Lock()
def eat1(name):
noodle_lock.acquire()
print('%s拿到了面条'%name)
chazi_lock.acquire()
print('%s拿到了叉子'%name)
print('%s吃面'%name)
chazi_lock.release()
noodle_lock.release()

def eat2(name):
chazi_lock.acquire()
print('%s拿到了叉子'%name)
noodle_lock.acquire()
print('%s拿到了面条' %name)
print('%s吃面'%name)
noodle_lock.release()
chazi_lock.release()


Thread(target=eat1,args=('alex',)).start()
Thread(target=eat2,args=('Egon',)).start()
Thread(target=eat1,args=('nezha',)).start()
Thread(target=eat2,args=('bossjin',)).start()

多线程的时候虽然有全局解释性锁,GIL 的存在,,GIL锁的是线程,同一时间只有一个线程能访问CPU,但是当实现多线程的时候,如果数据有多把锁,
但是由于CPU的时间片轮转法则,可能出现,多个线程拿了多个钥匙,不是一个一个线程拿了所有的钥匙,程序就会一直阻塞,这就是有名的死锁。
上面的例子用的Lock()是互斥锁

为了解决死锁问题,有了递归锁的出现,递归锁就像是一串钥匙,只能有一个人拿到所有钥匙,就不会出现死锁
from threading import Thread,RLock

chazi_lock = noodle_lock = RLock()
def eat1(name):
noodle_lock.acquire()
print('%s拿到了面条'%name)
chazi_lock.acquire()
print('%s拿到了叉子'%name)
print('%s吃面'%name)
chazi_lock.release()
noodle_lock.release()

def eat2(name):
chazi_lock.acquire()
print('%s拿到了叉子'%name)
noodle_lock.acquire()
print('%s拿到了面条' %name)
print('%s吃面'%name)
noodle_lock.release()
chazi_lock.release()


Thread(target=eat1,args=('alex',)).start()
Thread(target=eat2,args=('Egon',)).start()
Thread(target=eat1,args=('nezha',)).start()
Thread(target=eat2,args=('bossjin',)).start()
posted @ 2019-01-23 17:02  刀锋意志1  阅读(142)  评论(0编辑  收藏  举报