+ -
当前位置:首页 → 问答吧 → C++ 多线程 嵌入Python 并发出现 段错误(程序死掉)

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

时间:2011-04-21

来源:互联网

系统: 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;
}




作者: cdhumingyin   发布时间: 2011-04-21

为什么你所有的线程都使用同一个tid?

作者: iambic   发布时间: 2011-04-21