示例工程 25-c-extensions-ctypes-cffi

25-c-extensions-ctypes-cffi/04-gil-release/gil_release.py

python · 1.2 KB

"""对比 ctypes.CDLL(释放 GIL)与 PyDLL(持有 GIL)的线程并发。"""
 
from __future__ import annotations
 
import ctypes
import ctypes.util
import threading
import time
from collections.abc import Callable
 
USEC = 50_000
 
 
def load_libc(dll_type: Callable[[str | None], ctypes.CDLL]) -> ctypes.CDLL:
    name = ctypes.util.find_library("c")
    return dll_type(name)
 
 
def threaded_sleep(
    dll_type: Callable[[str | None], ctypes.CDLL],
    workers: int = 2,
) -> float:
    libc = load_libc(dll_type)
    libc.usleep.argtypes = [ctypes.c_uint]
    libc.usleep.restype = None
 
    def worker() -> None:
        libc.usleep(USEC)
 
    started = time.perf_counter()
    threads = [threading.Thread(target=worker) for _ in range(workers)]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    return time.perf_counter() - started
 
 
def main() -> None:
    cdll_time = threaded_sleep(ctypes.CDLL)
    pydll_time = threaded_sleep(ctypes.PyDLL)
    print(f"cdll: {cdll_time:.3f}s")
    print(f"pydll: {pydll_time:.3f}s")
    print(f"gil_released: {cdll_time < pydll_time * 0.8}")
 
 
if __name__ == "__main__":
    main()