python由于在实现多线程的情况下,由于GIL(全局解释器锁)的存在,只能实现伪线程,要想真正实现多线程,可以调用第三方的扩展,使用C语言编写一些需要实现多线程的业务逻辑。
最常用的调用C函数的方式,分别是c extension,Cython和ctypes。
c extension
介绍
python标准库包含了很多使用C开发的扩展模块,比如对性能要求很高的json库。开发者同样可以使用C开发扩展,这是最原始也是最底层的扩展python的方式。
示例
demomodule.c
python的扩展模块由以下几部分组成:
- Python.h
- C函数
- 接口函数(python代码调用的函数)到C函数的映射表
- 初始化函数
// pulls in the Python API
#include <Python.h>
// C function always has two arguments, conventionally named self and args
// The args argument will be a pointer to a Python tuple object containing the arguments.
// Each item of the tuple corresponds to an argument in the call’s argument list.
static PyObject *
demo_add(PyObject *self, PyObject *args)
{
const int a, b;
// convert PyObject to C values
if (!PyArg_ParseTuple(args, "ii", &a, &b))
return NULL;
return Py_BuildValue("i", a+b);
}
// module's method table
static PyMethodDef DemoMethods[] = {
{"add", demo_add, METH_VARARGS, "Add two integers"},
{NULL, NULL, 0, NULL}
};
// module’s initialization function
PyMODINIT_FUNC
initdemo(void)
{
(void)Py_InitModule("demo", DemoMethods);
}
setup.py
编译扩展模块通常使用distutils或setuptools,它会自动调用gcc完成编译和链接。
from distutils.core import setup, Extension
module1 = Extension('demo',
sources = ['demomodule.c']
)
setup (name = 'a demo extension module',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1])
执行
python setup.py build_ext --inplace
会在当前目录生

本文介绍了Python在GIL限制下如何通过c extension、Cython和ctypes调用C语言实现多线程。详细讲解了每个方法的原理、示例及编译过程,并进行了性能基准测试。
最低0.47元/天 解锁文章
285

被折叠的 条评论
为什么被折叠?



