import threading
import time
def test1():
if mutex_a.acquire():
print(str(threading.current_thread()) + '----do1----up')
time.sleep(1)
if mutex_b.acquire():
print(str(threading.current_thread()) + '----do1---down')
mutex_b.release()
mutex_a.release()
def test2():
if mutex_b.acquire():
print(str(threading.current_thread()) + '----do2----up')
time.sleep(1)
if mutex_a.acquire():
print(str(threading.current_thread()) + '----do2----down')
mutex_a.release()
mutex_b.release()
if __name__ == '__main__':
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
mutex_a = threading.Lock()
mutex_b = threading.Lock()
t1.start()
t2.start()
# 在线程1运行的test1中锁a生效,在线程2的test2中锁b生效,而在test1向下时想要获取锁b,在test2向下时想要获取锁a,导致死锁发生
输出:
<Thread(Thread-1, started 140486659753728)>----do1----up
<Thread(Thread-2, started 140486651361024)>----do2----up
.......暂停在了此处,需要ctrl+c退出。
说明:
避免死锁
- 程序设计时要尽量避免(银行家算法)
- 添加超时时间等