[python-win32] Embedded Python and multithreading
thorsten riesberg
ThorstenRiesberg at gmx.de
Thu Jun 26 08:50:11 CEST 2008
Hi all,
can anybody explain me why the following code is not running:
//
#include "stdafx.h"
#include <windows.h>
#include <strsafe.h>
#include <stdio.h>
#include "Python.h"
DWORD WINAPI Callback1( LPVOID lpvData){
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
PyThreadState* tcur = PyThreadState_Get() ;
PyThreadState_Swap(NULL);
PyThreadState_Clear(tcur);
PyThreadState_Delete(tcur);
// release the GIL as PyEval_InitThreads
// implicitly acquires the GIL
PyEval_ReleaseLock();
PyGILState_STATE gstate;
for(int i = 0; i < 20; i++){
gstate = PyGILState_Ensure();
pName = PyString_FromString("test1");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "test");
if (PyCallable_Check(pFunc))
{
pValue = PyObject_CallObject(pFunc, NULL);
}
else {
PyErr_Print();
}
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
PyGILState_Release(gstate);
Sleep(1000);
}
return TRUE;
};
DWORD WINAPI Callback2( LPVOID lpvData){
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
PyThreadState* tcur = PyThreadState_Get() ;
PyThreadState_Swap(NULL);
PyThreadState_Clear(tcur);
PyThreadState_Delete(tcur);
// release the GIL as PyEval_InitThreads
// implicitly acquires the GIL
PyEval_ReleaseLock();
PyGILState_STATE gstate;
for(int i = 0; i < 20; i++){
gstate = PyGILState_Ensure();
pName = PyString_FromString("test1");
pModule = PyImport_Import(pName);
// pDict and pFunc are borrowed references
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "test");
if (PyCallable_Check(pFunc))
{
pValue = PyObject_CallObject(pFunc, NULL);
}
else {
PyErr_Print();
}
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
PyGILState_Release(gstate);
Sleep(1000);
}
return TRUE;
};
int main(int argc, char *argv[])
{
Py_Finalize();
Py_Initialize();
PyEval_InitThreads();
DWORD threadID;
CreateThread(NULL,10000 ,Callback1,(LPVOID)NULL,0,&threadID);
CreateThread(NULL,10000 ,Callback2,(LPVOID)NULL,0,&threadID);
getchar();
Py_Finalize();
return 0;
}
If I start just one Thread:
CreateThread(NULL,10000 ,Callback1,(LPVOID)NULL,0,&threadID);
//CreateThread(NULL,10000 ,Callback2,(LPVOID)NULL,0,&threadID);
every thing is fine.
The second thread stops with:
Fatal Python error: PyThreadState_Get: no current thread
Thanks in advance
Thorsten
--
GMX startet ShortView.de. Hier findest Du Leute mit Deinen Interessen!
Jetzt dabei sein: http://www.shortview.de/?mc=sv_ext_mf@gmx
More information about the python-win32
mailing list