如果 C/C++ Python3 扩展托管 http 服务器并调用 python 代码作为请求处理程序,如何处理并发?

How to handle concurrency if C/C++ Python3 extension hosting a http server and calling python code as request handler?

我尝试创建一个 Python 扩展来托管 HTTP 服务器。当一个特定的请求进来时,扩展调用来自扩展消费者的 Python 代码来处理请求。由于 HTTP 服务器本质上是多线程的,因此 controller/Python-code 将被并行调用。

根据 Python Document,我尝试做如下的事情(删除了所有错误处理代码分支以使其更简单)

static string CallingPythonFunc(string input)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    PyObject *arglist;
    PyObject *result;

    /* Time to call the callback */

    PyGILState_Release(gstate);
    return output;
}

my_python_func 可以很简单,如下所示:

def foo(input):
    return input+"123"

但显然如果同时有两个请求进来,上面的代码就会死锁。

我还发现了一些其他的sample1, sample2 and Whosebug answer1, answer2。但是似乎两个示例代码都是自己创建线程,我的例子是线程是由 http 服务器创建的。 Whosebug 的两个答案让人感到困惑。我认为我上面的代码应该等待 GIL 可用,然后 运行 python 回调代码,然后从临界区中退出。但是我上面显示的好像不是这样。

最终,我通过与 Python 的一些大师交谈得到了解决方案:我需要调用 PyEval_InitThreads() 并用 [=11 包装创建非 Python 线程的代码=] 和 Py_END_ALLOW_THREADS.