Invalid thread state for this thread

Martin Evans martin at browns-nospam.co.uk
Thu May 24 10:52:40 EDT 2007


I know this has been seen before but it is not making too much sense (after 
reading many posts). It all appears to work fine but then dies after about 
40 invocations.

My app has Python embedded, it is embedded as part of a dll which 
initializes python and finalizes on load and unload (see below). When a 
script needs to be run, I create a new thread, let the script complete and 
close the thread.

The thread contains the following type arrangement:

PythonThread()
{
  hScriptFile = OpenScriptFile(m_szActiveScript);
  PyEval_AcquireLock();
  pInterpreter = Py_NewInterpreter();
  Py_SetProgramName(szModuleFileName);
  PyRun_SimpleFile(hScriptFile,m_szActiveScript);
  PyErr_Clear();
  Py_EndInterpreter(pInterpreter);
  PyEval_ReleaseLock();
}

This appears to work fine accept that after around 30-40 invocations I 
always get the "Invalid thread state for this thread". ie the app and dll 
stay loaded and I click my "run" button manually about 40 times. In this 
test it is a simple "hello world" type script. The size of the script does 
not appear to matter.

The dll is coded something like this:

DllLoad()
{
  Py_Initialize();
  PyEval_InitThreads();
  m_mainThreadState = PyThreadState_Get();
  PyEval_ReleaseLock();
}

DllUnload()     (not called as part of this test)
{
  PyEval_AcquireLock();
  PyThreadState_Swap(m_mainThreadState);
  Py_Finalize();
}

The app has been designed to allow a second interpreter to run independently 
(thus the need for multiple thread support) and this also appears to work 
fine, but for this test only this one thread was used. I have a compiled 
version of 2.4.2.

Any ideas would be appreciated.

Martin 





More information about the Python-list mailing list