线程死锁和递归锁

'''


import threading
import time
class mythread(threading.Thread):
def A(self):
locka.acquire() #获取锁
print(self.name,"getlocka",time.ctime())
time.sleep(3)
lockb.acquire()
print(self.name,"getlockb",time.ctime())
lockb.release() #释放锁
locka.release()


def B(self):
lockb.acquire()
print(self.name,"getlockb",time.ctime())
time.sleep(2)
locka.acquire()
print(self.name,"getlocka",time.ctime())
locka.release()
lockb.release()
def run(self):
self.A()
self.B()

if __name__=="__main__":
locka=threading.Lock()
lockb=threading.Lock()
threads=[]

for i in range(5):
threads.append(mythread())#mythread()为实例化对象;将实例化5次并追加到列表中
print(threads)
for t in threads: #遍历列表中的实例化对象,分分别进行启动,并调用其中run方法
t.start()
for t in threads:
t.join()
'''
'''
#输出结果:
Thread-1 getlocka Wed Jan 5 15:58:16 2022
Thread-1 getlockb Wed Jan 5 15:58:19 2022
Thread-1 getlockb Wed Jan 5 15:58:19 2022
Thread-2 getlocka Wed Jan 5 15:58:19 2022
当循环将线程追加到threads列表中以后,首先将线程1取出去调用run方法,当线程1获取到锁A,去执行打印,然后去获取B锁,执行打印
随后释放B锁,A锁;同时线程1去执行B函数获取b锁,并打印;再休息了2s后想要去获取A锁,而与此同时线程2已经执行了A函数获取了A锁将要获取B锁,
因为线程1没有执行到释放B锁,线程2没法拿到B锁,线程2没有释放A锁,线程1没有办法拿到B锁;导致程序无法执行,死在当前程序中
'''
# 解决方法使用,递归锁,其就是一把锁,而此锁可以被重复使用
# 如下:
import threading
import time
class mythread(threading.Thread):
def A(self):
lock.acquire()
print(self.name,"getlocka",time.ctime())
time.sleep(3)
lock.acquire()
print(self.name,"getlockb",time.ctime())
lock.release()
lock.release()


def B(self):
lock.acquire()
print(self.name,"getlockb",time.ctime())
time.sleep(2)
lock.acquire()
print(self.name,"getlocka",time.ctime())
lock.release()
lock.release()
def run(self):
self.A()
self.B()

if __name__=="__main__":
# locka=threading.Lock()
# lockb=threading.Lock()
lock=threading.RLock() #创建递归锁
threads=[]

for i in range(5):
threads.append(mythread())#mythread()为实例化对象;将实例化5次并追加到列表中
print(threads)
for t in threads: #遍历列表中的实例化对象,分分别进行启动,并调用其中run方法
t.start()
for t in threads:
t.join()
#输出结果:
"""
Thread-1 getlocka Wed Jan 5 17:18:39 2022
Thread-1 getlockb Wed Jan 5 17:18:42 2022
Thread-2 getlocka Wed Jan 5 17:18:42 2022
Thread-2 getlockb Wed Jan 5 17:18:45 2022
Thread-2 getlockb Wed Jan 5 17:18:45 2022
Thread-2 getlocka Wed Jan 5 17:18:47 2022
Thread-4 getlocka Wed Jan 5 17:18:47 2022
Thread-4 getlockb Wed Jan 5 17:18:50 2022
Thread-4 getlockb Wed Jan 5 17:18:50 2022
Thread-4 getlocka Wed Jan 5 17:18:52 2022
Thread-1 getlockb Wed Jan 5 17:18:52 2022
Thread-1 getlocka Wed Jan 5 17:18:54 2022
Thread-3 getlocka Wed Jan 5 17:18:54 2022
Thread-3 getlockb Wed Jan 5 17:18:57 2022
Thread-3 getlockb Wed Jan 5 17:18:57 2022
Thread-3 getlocka Wed Jan 5 17:18:59 2022
Thread-5 getlocka Wed Jan 5 17:18:59 2022
Thread-5 getlockb Wed Jan 5 17:19:02 2022
Thread-5 getlockb Wed Jan 5 17:19:02 2022
Thread-5 getlocka Wed Jan 5 17:19:04 2022

"""
对于A方法,当获取到大锁的时候,再去获取小锁,然后分别释放小锁和大锁完毕以后,所有线程都会去抢获取锁的资源,谁先抢到,哪个线程则会进行执行

上一篇:如何用人机协同提高客服效率?阿里巴巴客服助手诞生了


下一篇:新零售浪潮下,人货动作如何数字化?