c语言多线程转python多线程,C语言中多线程python扩展中的Segfault

我有一个非常精简的示例,它创建了一个似乎无法摆脱的segfault。Python脚本在扩展中调用一个C函数,该函数使用pthreads创建一个新线程。在新线程中,我在python调用(PyRun_SimpleString)中使用PyGILState_sure和PyGILState_Release,但可能我没有正确使用它们,或者错过了其他一些步骤。在receive_audio函数中注释掉python调用,segfault不再发生。有什么想法吗?在

输出:

python库/测试.py

(主线程)initmodule完成

(主线程)调用run_Thread()

(主线程)创建线程

(新线程)在receive_audio()-获取GIL

(新线程)python打印!

(新线程)在receive_audio()-发布的GIL

(新线程)循环0

分段故障

C代码如下:PyMODINIT_FUNC streamaudio() {

PyObject *m = Py_InitModule("streamaudio", methods);

PyEval_InitThreads();

mainThreadState = PyThreadState_Get();

PyEval_ReleaseLock();

printf("(Main Thread) initmodule complete\n");

}

static PyObject* run_thread(PyObject* self, PyObject* args)

{

int ok, stream_id;

PyGILState_STATE gstate;

gstate = PyGILState_Ensure();

ok = PyArg_ParseTuple(args, "i", &stream_id);

PyRun_SimpleString("print '(Main Thread) Creating thread'\n");

int rc = pthread_create(&thread, NULL, receive_audio, (void*)stream_id);

PyRun_SimpleString("print '(Main Thread) Thread created'\n");

PyGILState_Release(gstate);

return Py_BuildValue("i", rc);

}

void* receive_audio(void *x)

{

printf("(New Thread) In receive_audio() - acquiring GIL\n");

PyGILState_STATE gstate;

gstate = PyGILState_Ensure();

PyRun_SimpleString("print '(New Thread) python print!'\n");

PyGILState_Release(gstate);

printf("(New Thread) In receive_audio() - released GIL\n");

int i;

for (i = 0; i < 100; i++) {

printf("(New Thread) Looping %d\n", i);

sleep(1);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值