Skip to content

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()

构建时间:11/21/2025, 1:28:39 PM | 本博客内容均为自己学习,如内容涉及侵权,请联系邮箱:pangzl0215@163.com