【发布时间】:2011-09-29 13:48:09
【问题描述】:
我正在用 C 编写一个多线程程序。在创建线程之前,通过调用 Py_Initialize() 初始化全局 python 环境。然后,在每个创建的线程中,共享全局python环境,每个线程调用一个python方法,并将参数转换为C。一切正常,直到这里。
当我在加载的 python 模块中使用time.sleep() 时,C 程序会引发Segmentation Fault。此外,加载的 python 模块应该加载另一个 C 库以继续工作。我编写了以下愚蠢的计数器库来测试它:
# python part, call the counter function
lib = ctypes.cdll.LoadLibrary(libpycount.so)
for i in xrange(10):
lib.count()
// C part, dummy countings
#include <stdio.h>
int counter = 1;
void
count() {
printf("counter:%d \n", counter);
counter++;
}
我想这可能是因为我没有以正确的方式管理复杂的线程创建。我在 python 文档中找到了Non-Python created threads。
有什么想法或建议吗?
【问题讨论】:
-
您是否真的按照您找到的文档中的建议进行操作?您如何在调用 Python 的代码中获取 GIL?
-
@Thomas Wouters 我用过文档中提到的
PyGILState_STATE gstate;、gstate = PyGILState_Ensure();和PyGILState_Release(gstate);。
标签: python c multithreading