GIL什么时候发布?

When the GIL is released?

今天,我编写了一个简单的脚本,允许我对 openstack swift 服务器进行基准测试:

import swiftclient
import uuid
from concurrent.futures import ThreadPoolExecutor

def create():
    client = swiftclient.client.Connection(
        user='', key='',
        authurl='https://auth/', auth_version='2.0',
        tenant_name='',
        os_options={'tenant_id': '',
                    'region_name': ''})
    while True:
        uid = str(uuid.uuid4())
        client.put_object(container='', obj=uid, contents=b'\x00')

executor = ThreadPoolExecutor(max_workers=100)
for _ in range(100):
    executor.submit(create)

一切顺利,但我注意到一件奇怪的事情,该过程的使用率超过 CPU 的 400%。 这是怎么回事,因为 GIL 不应允许使用超过 100% 的 CPU?

GIL 只能同时阻止来自 运行 的两个 python 命令(导致它一次只能使用一个 CPU)。但是任何调用 C 的 python 代码都有可能释放 GIL,直到 C 代码必须再次与 Python SDK 交互,通常是在它 returns 并将结果编组回来时转化为 Python 个值。因此,如果应用程序大量使用 C 库,则可能会有高度线程化的 python 应用程序。

来自 GIL

上的 python wiki

Note that potentially blocking or long-running operations, such as I/O, image processing, and NumPy number crunching, happen outside the GIL. Therefore it is only in multithreaded programs that spend a lot of time inside the GIL, interpreting CPython bytecode, that the GIL becomes a bottleneck.