You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中存在GIL时,线程仍可能产生死锁吗?(非多进程场景)

Python中存在GIL时,线程仍可能产生死锁吗?(非多进程场景)

是的,即使Python存在全局解释器锁(GIL),线程仍然可能产生死锁。

以下是会触发死锁的代码示例:

import threading
import time

# 两个资源锁
resource1 = threading.Lock()
resource2 = threading.Lock()

def function1():
    with resource1:
        print("Thread 1 acquired resource 1")
        time.sleep(3)
        with resource2:
            print("Thread 1 acquired resource 2")
            time.sleep(3)

def function2():
    with resource2:
        print("Thread 2 acquired resource 2")
        time.sleep(3)
        with resource1:
            print("Thread 2 acquired resource 1")
            time.sleep(3)

# 创建并启动线程
thread1 = threading.Thread(target=function1)
thread2 = threading.Thread(target=function2)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

print("Both threads finished execution")

原理说明

GIL仅负责限制同一时间只有一个线程执行Python字节码,但它不会干预用户手动创建的锁资源的获取与释放逻辑。当多个线程按照相反顺序获取多个锁时,就会出现经典的循环等待死锁:

  • Thread 1持有resource1,等待resource2
  • Thread 2持有resource2,等待resource1
    双方都无法继续执行,也不会主动释放已持有的锁,最终陷入死锁。代码中的time.sleep(3)是为了放大竞态条件,确保两个线程有足够时间分别拿到第一个锁,稳定触发死锁场景。

内容的提问来源于stack exchange,提问作者user3761555

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 02:44:51