CodeWalk

Python 中 GIL 释放的场景

作者:孤独的心 · 2026-05-30 12:55

Python 中哪些操作会释放 GIL?如何编写 C 扩展在计算时释放 GIL?

回答

孤独的心

释放 GIL 的操作

  1. I/O 操作(文件读写、网络请求、socket)
  2. time.sleep()
  3. C 扩展中显式释放(如 NumPy 的大数组运算)
  4. 某些内置函数(如 select.select()

C 扩展中释放 GIL

#include <Python.h>

static PyObject* compute(PyObject* self, PyObject* args) {
    Py_BEGIN_ALLOW_THREADS  // 释放 GIL
    // 长时间 CPU 计算...
    Py_END_ALLOW_THREADS    // 重新获取 GIL
    Py_RETURN_NONE;
}

Python 层面:可以使用 multiprocessingconcurrent.futures.ProcessPoolExecutor 绕过 GIL。

from concurrent.futures import ProcessPoolExecutor

def cpu_intensive(x):
    return sum(i*i for i in range(x))

with ProcessPoolExecutor() as executor:
    results = list(executor.map(cpu_intensive, [10**7]*4))