C++ 多线程 嵌入Python 并发出现 段错误(程序死掉)

cdhumingyin 2011-04-21 09:22:17
系统: suse11
开发语言C++
C++ 多线程中调用 Python 出现段错误

一个线程使用程序正常 ,启动2个及以上的线程并发调用Python 出现段错误
并且每次调用出现段错误地方不同
自我分析感觉如果有一个线程在调用解释器,另一个线程也并发调用解释器 就出现该错误(不知道是否是多个线程引用了同一个解释器的原因)

然后在每个线程中调用 Py_NewInterpreter()创建子解释器 仍未解决问题

以下附上代码


#include<iostream>
#include <pthread.h>
#include<stdio.h>
#include<Python.h>
#include<map>
#include <sys/types.h>
#include<pthread.h>
#include<sys/syscall.h>
using namespace std;

static int iCount =0;

void* TestThreadFun(void *arg)
{

PyThreadState* mainThreadState = NULL;

PyThreadState* nts = Py_NewInterpreter();

std::string strPyPath = "/usr/local/icache/src/css/iEngineFlow/config";
std::string strTmp = "sys.path.append('" + strPyPath + "')";

int iPyRet=0;
iPyRet = PyRun_SimpleString("import sys");

if (0 != iPyRet)
{
cout<<"import sys failed !"<<endl;
}

iPyRet = PyRun_SimpleString("sys.path.append('./')");
if (0 != iPyRet)
{
cout<<"import ./ failed !"<<endl;
}
iPyRet = PyRun_SimpleString(strTmp.c_str());
if (0 != iPyRet)
{
cout<<"import "<<strTmp <<" failed !"<<endl;
}

/*
Call python Method here

*/

Py_EndInterpreter(nts);

return NULL;
}


pthread_t tid = 0;
int main()
{
Py_Initialize();
int ret = 0;
PyEval_InitThreads();
int i =0;
for (;i<2;i++)
{
std::cout<<"thread"<<i<<" begin"<<endl;
ret = pthread_create(&tid, NULL, TestThreadFun, &tid);

}
sleep(5);
PyEval_ReleaseLock();
return 0;
}
...全文
575 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
camel_flying 2011-10-26
  • 打赏
  • 举报
回复
注释掉这行就行了PyThreadState* nts = Py_NewInterpreter(),不过我没有见过在线程里面调用这个函数的用法!
fibbery 2011-04-22
  • 打赏
  • 举报
回复
我不太会在C/C++中嵌入Python,对于你的代码,我有以下疑问和建议:
1、PyThreadState* nts = Py_NewInterpreter(); 函数的返回值类型是PyThreadState*对吗?
2、在多线程环境下,调用的函数都应该是线程安全的,对于你使用的py api,我没有看到与特定线程相关的interpreter,所以,我判断,是不是你的使用方法有问题。
3、你将线程中的代码全部注释掉,一点一点的放开,看看在什么时候,产生段错误。
cdhumingyin 2011-04-22
  • 打赏
  • 举报
回复
谢谢提示,正在试验中
angel_su 2011-04-22
  • 打赏
  • 举报
回复
没看到哪里有上锁自己管理切换线程状态,即使每个线程中调用 Py_NewInterpreter(),在此之前也都要先作这个基本的吧...
iambic 2011-04-21
  • 打赏
  • 举报
回复
为什么你所有的线程都使用同一个tid?
iambic 2011-04-21
  • 打赏
  • 举报
回复
你怎么知道不是这个原因导致的?
cdhumingyin 2011-04-21
  • 打赏
  • 举报
回复
我关注的不是tid这个问题,谢谢!

37,718

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧