Help me please..
I'm trying to call python scripts from different C++ threads and faced some problem.
main:
Py_Initialize();
PyEval_InitThreads();
PyThreadState *mainThreadState = PyThreadState_Get();
PyEval_ReleaseLock();
PyInterpreterState *mainInterpreterState = mainThreadState->interp;
...
//creating threads with myThreadState per thread
PyEval_AcquireLock();
PyThreadState *myThreadState = PyThreadState_New(mainInterpreterState);
PyEval_ReleaseLock();
//running threads
...
PyEval_RestoreThread(mainThreadState);
Py_Finalize();
run() function in thread object:
PyEval_AcquireLock();
PyThreadState_Swap(m_threadState);
...
script = "f = open('file_for_this_thread','w')\n"
"print f\n"
"f.write('111')\n"
"print f.fileno()\n"
PyRun_SimpleString( script );
...
PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
'print f' displays correct file info for each file
But something is wrong, because second 'print f' prints the same for different threads and the output (if there will be the one) will go to one file instead of different file for each thread
File handlers become equal if i insert time.sleep(1) instead of f.write, too
Nothing crashes..
also tried using PyGILState_Ensure/PyGILState_Release, same effect
main:
Py_Initialize();
PyEval_InitThreads();
PyThreadState* mainThreadState = PyEval_SaveThread();
...
//creating and running threads
...
PyEval_RestoreThread(mainThreadState);
Py_Finalize();
locker:
TPyScriptThreadLocker:
PyGILState_STATE m_state;
public:
TPyScriptThreadLocker(): m_state(PyGILState_Ensure() {}
~TPyScriptThreadLocker() { PyGILState_Release(m_state); }
run() function in thread object:
TPyScriptThreadLocker lock;
...
script = "f = open('file_for_this_thread','w')\n"
"print f.fileno()\n"
"f.write('111')\n"
"print f.fileno()\n"
PyRun_SimpleString( script );
I know that multithreading in python is not good idea in most cases, but now I want to know what is wrong with this code..
Python 2.7
info from http://www.linuxjournal.com/article/3641?page=0,2
source: http://files.mail.ru/9D4TEF pastebin: http://pastebin.com/DfFT9KN3