基于 pybind11 的 Python C++ 扩展与 GIL 锁绕过实践
在 Python 开发中,全局解释器锁(GIL)导致多线程无法充分利用多核 CPU 资源,尤其在计算密集型场景下性能受限。虽然多进程方案可以规避 GIL,但其内存开销和通信成本较高。通过 C++ 编写扩展模块并利用 pybind11 释放 GIL,是实现高性能并发计算的有效途径。
1. C++ 扩展实现
以下代码展示了如何使用 pybind11 封装 C++ 多线程逻辑。关键在于使用 py::gil_scoped_release 在原生线程中释放锁,并在回调 Python 函数前重新获取锁。
// native_module.cpp
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <thread>
#include <vector>
namespace py = pybind11;
// 单个工作线程任务
void worker_func(int worker_id, int loop_count, py::function notify_func) {
long long accumulator = 1;
// 模拟密集计算
for (int k = 1; k <= loop_count; ++k) {
accumulator *= k;
}
// 调用 Python 回调前必须重新获取 GIL
py::gil_scoped_acquire lock;
notify_func(worker_id, "Task Finished");
}
// 并行执行入口
void parallel_executor(int thread_count, int loop_count, py::function notify_func) {
// 释放 GIL 以允许原生多线程并行
py::gil_scoped_release unlock;
std::vector<std::thread> thread_pool;
for (int i = 0; i < thread_count; ++i) {
thread_pool.emplace_back(worker_func, i, loop_count, notify_func);
}
for (auto &t : thread_pool) {
t.join();
}
}
PYBIND11_MODULE(native_module, m) {
m.def("parallel_executor", ¶llel_executor, "Run tasks with GIL released");
m.def("worker_func", &worker_func, "Single worker task");
}
2. 模块编译配置
使用 setuptools 配合 pybind11 进行构建。确保已安装 pybind11 库,Windows 环境下需配置相应的 C++ 编译工具链。
# build_config.py
import setuptools
from setuptools import Extension
import pybind11
import platform
include_dir = pybind11.get_include()
compile_flags = []
if platform.system() == 'Windows':
compile_flags.append('/std:c++latest')
extensions = [
Extension(
'native_module',
sources=['native_module.cpp'],
include_dirs=[include_dir],
language='c++',
extra_compile_args=compile_flags
)
]
setuptools.setup(
name='native_module',
version='1.0.0',
ext_modules=extensions,
)
执行构建命令生成动态链接库:
python build_config.py build develop
3. 性能对比测试
通过基准测试对比 C++ 原生多线程与 Python 线程池在相同计算负载下的表现。
# benchmark.py
import native_module
import time
import threading
from multiprocessing.dummy import Pool
def on_complete(uid, msg):
pass
def python_worker(loops, callback):
native_module.worker_func(uid=threading.get_ident(), loop_count=loops, notify_func=callback)
# 测试 C++ 多线程
start_time = time.time()
native_module.parallel_executor(100, 5000000, on_complete)
cpp_duration = time.time() - start_time
print(f'C++ 原生多线程耗时:{cpp_duration}')
# 测试 Python 多线程
task_params = [5000000] * 100
start_time = time.time()
with Pool(100) as executor:
executor.map(lambda x: python_worker(x, on_complete), task_params)
py_duration = time.time() - start_time
print(f'Python 多线程耗时:{py_duration}')
测试结果显示,在释放 GIL 的情况下,C++ 多线程方案在处理计算密集型任务时相比 Python 多线程有显著的性能提升,通常可达到数倍至十倍以上的加速效果。