5. 死锁
死锁,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象。
python
import threading
import time
lock1 = threading.Lock()
lock2 = threading.Lock()
def task1():
lock1.acquire()
print("task1 获取到 lock1")
time.sleep(1)
lock2.acquire()
print("task1 获取到 lock2")
lock2.release()
lock1.release()
def task2():
lock2.acquire()
print("task2 获取到 lock2")
time.sleep(1)
lock1.acquire()
print("task2 获取到 lock1")
lock1.release()
lock2.release()
t1 = threading.Thread(target=task1)
t1.start()
t2 = threading.Thread(target=task2)
t2.start()