I'm using this code for python multithreading scripts (got it from web):
class PyMainGuard
{
public:
PyMainGuard()
{
Py_Initialize();
PyEval_InitThreads();
mGilState = PyGILState_Ensure();
mThreadState = PyEval_SaveThread();
}
~PyMainGuard()
{
PyEval_RestoreThread( mThreadState );
PyGILState_Release( mGilState );
Py_Finalize();
}
private:
PyGILState_STATE mGilState;
PyThreadState* mThreadState;
};
class PyThrGuard
{
public:
PyThrGuard()
{
mMainGilState = PyGILState_Ensure();
mOldThreadState = PyThreadState_Get();
mNewThreadState = Py_NewInterpreter();
PyThreadState_Swap( mNewThreadState );
mSubThreadState = PyEval_SaveThread();
mSubGilState = PyGILState_Ensure();
}
~PyThrGuard()
{
PyGILState_Release( mSubGilState );
PyEval_RestoreThread( mSubThreadState );
Py_EndInterpreter( mNewThreadState );
PyThreadState_Swap( mOldThreadState );
PyGILState_Release( mMainGilState );
}
private:
PyGILState_STATE mMainGilState;
PyThreadState* mOldThreadState;
PyThreadState* mNewThreadState;
PyThreadState* mSubThreadState;
PyGILState_STATE mSubGilState;
};
In main thread I need to create PyMainGuard, and then in every single thread I have to create PyThrGuard - that creates there independent interpretator, that allows me to use threading without problem. But they still share same resources.
For example, if I will use this scrypts:
import win32evtlog
import time
server = "localhost"
logtype = "TestEventSource"
archfile = "C:\test.txt"
EVENTLOG_SUCCESS = 0
hWriteLog = win32evtlog.RegisterEventSource(None, logtype.decode('unicode-escape'))
strings = []
for x in range(0, 5):
del strings[:]
for y in range(0, 3):
a = "Python run [%d] with part %d" % (x, y)
strings.append(a.decode('unicode-escape'))
time.sleep(2)
win32evtlog.ReportEvent(hWriteLog, EVENTLOG_SUCCESS, 0, 515, None, strings, None)
win32evtlog.DeregisterEventSource(hWriteLog)
Sometimes I can get crash, sometimes there can be created events in windows log with more or less then 3 lines of text (i.e. different threads will write to one event, having same EventHandle, I guess).
Everything looks like my threads still works in same interpeter, not in different ones. Or there is a chance that win32evtlog is very thread unsafe, it loads just ones (not for every interpreter, as I want) and creates such problems.
Question is: how to achieve different interpreters for each thread?