python3 一 多线程死锁问题及解决方案
死锁:前提是有多个锁
所谓死锁: 是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程
- 在线程间共享多个资源的时候,如果两个线程分别占有一部分资源并且同时等待对方的资源时,就会造成死锁。
- 尽管死锁很少发生,但一旦发生就会造成应用的停止响应。
产生死锁的代码:
import threading
import time
def test1():
mA.acquire()
print("test1--上锁A")
time.sleep(1)
mB.acquire()
print("test1---上锁B")
mA.release()
print("test1---解锁A")
mB.release()
print("test1---解锁B")
def test2():
mB.acquire()
print("test2---上锁B")
time.sleep(1)
mA.acquire()
print("test2--上锁A")
mB.release()
print("test2---解锁B")
mA.release()
print("test2---解锁A")
mA = threading.Lock()
mB = threading.Lock()
def main():
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
if __name__ == '__main__':
main()
运行结果:
解决死锁问题
- 添加超时时间
- 银行家算法
- 添加超时时间
import threading
import time
def test1():
mA.acquire()
print("test1--上锁A")
time.sleep(1)
mB.acquire(timeout=3) # 在此处添加了超时时间,此处上锁超过3秒自动解锁
print("test1---上锁B")
mA.release()
print("test1---解锁A")
# mB.release() 因为是死锁,所有在上面代码一定会达到超时时间自动解锁,执行到此处时会报错 (release unlocked lock)无法解锁已经解开的锁,要注释掉
print("test1---解锁B")
def test2():
mB.acquire()
print("test2---上锁B")
time.sleep(1)
mA.acquire()
print("test2--上锁A")
mB.release()
print("test2---解锁B")
mA.release()
print("test2---解锁A")
运行结果:
test1--上锁A
test2---上锁B
test1---上锁B
test1---解锁A
test1---解锁B
test2--上锁A
test2---解锁B
test2---解锁A