第二次运行的线程会出错

时间:2014-03-14 19:07:24

标签: python c++ multithreading visual-studio-2012

我在Windows中使用线程将c ++编写的插件连接到python脚本。在会话期间多次调用该线程

问题:

第二次调用调用python脚本的工作线程时会发生这种情况:

- > .exe程序崩溃了代码: "运行时错误! 程序:xxx.exe。 此应用程序已请求Runtime以不寻常的方式终止它。请联系应用程序的支持团队以获取更多信息"

- >在Visual Studio中它说:" xxx.exe中0x7735C41F的第一次机会异常:Microsoft C ++异常:内存位置0x06A9F840处的CInvalidArgException。 如果存在此异常的处理程序,则可以安全地继续该程序。"

引导我进入mlock.c

这些行
void __cdecl _unlock (
    int locknum
    )
{
    /*
     * leave the critical section.
     */
    LeaveCriticalSection( _locktable[locknum].lock );
}

我在哪里没有正确处理异常?

我从调试中注意到,最后一行的_endthread()从未到达,我不明白为什么。这是问题的根源吗?

代码:

这是工作线程的代码:

void py_embed (void*data){

char *argv[4]={"PythonPlugIn2","bridge","test_callsign","MAH543"};
int argc=4;

ofstream textfile3;
textfile3.open("FP_python_embed.txt");

PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
PyThreadState *mainThreadState,*myThreadState,*tempState;
PyInterpreterState *mainInterpreterState;

//To inform the interpreter about paths to Python run-time libraries
Py_SetProgramName(argv[0]);

// Initialize the Python Interpreter
Py_Initialize();

// Initialize thread support
PyEval_InitThreads();

// Save a pointer to the main PyThreadState object
mainThreadState = PyThreadState_Get();

// Get a reference to the PyInterpreterState
mainInterpreterState = mainThreadState->interp;

// Create a thread state object for this thread
myThreadState = PyThreadState_New(mainInterpreterState);

// Release global lock
PyEval_ReleaseLock();

// Acquire global lock
PyEval_AcquireLock();

// Swap in my thread state
tempState = PyThreadState_Swap(myThreadState);

// Build the name object
pName = PyString_FromString(argv[1]);

// Load the module object
pModule = PyImport_Import(pName);

// pDict is a borrowed reference 
pDict = PyModule_GetDict(pModule);

// pFunc is also a borrowed reference 
pFunc = PyDict_GetItemString(pDict, argv[2]);

//Do the Python things
PyObject *pArgs2, *pValue2;
pArgs2=Py_BuildValue("(s)",argv[3]);
pValue2 = PyObject_CallObject(pFunc, pArgs2);
textfile3<<PyInt_AsLong(pValue2)<<endl<<" worked1";
textfile3.close();

// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);

// Swap out the current thread
PyThreadState_Swap(tempState);

// Release global lock
PyEval_ReleaseLock();

// Clean up thread state
PyThreadState_Clear(myThreadState);
PyThreadState_Delete(myThreadState);

// Finish the Python Interpreter
Py_Finalize();

_endthread();
};

我做的是从主线程调用它(在工作线程完成之前关闭):

handle=(HANDLE) _beginthread(py_embed,0,NULL);

注意:与此相关的问题2为here

0 个答案:

没有答案