call python script from C++ threads, GIL
<p>Help me please..<br>
I'm trying to call python scripts from different C++ threads and faced some problem.</p>

<p>main:  </p>

<pre><code>Py_Initialize();    
PyEval_InitThreads();
PyThreadState *mainThreadState = PyThreadState_Get();
PyEval_ReleaseLock();
PyInterpreterState *mainInterpreterState = mainThreadState-&gt;interp;
...
//creating threads with myThreadState per thread
    PyEval_AcquireLock();
    PyThreadState *myThreadState = PyThreadState_New(mainInterpreterState);
    PyEval_ReleaseLock();
//running threads
...
PyEval_RestoreThread(mainThreadState);
Py_Finalize();
</code></pre>

<p>run() function in thread object:</p>

<pre><code>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();
</code></pre>

<p>'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<br>
File handlers become equal if i insert time.sleep(1) instead of f.write, too
Nothing crashes..</p>

<p>also tried using PyGILState_Ensure/PyGILState_Release, same effect<br>
main:</p>

<pre><code>Py_Initialize();
PyEval_InitThreads();
PyThreadState*  mainThreadState = PyEval_SaveThread();
...
//creating and running threads
...
PyEval_RestoreThread(mainThreadState);
Py_Finalize();
</code></pre>

<p>locker:</p>

<pre><code>TPyScriptThreadLocker:
    PyGILState_STATE m_state;
public:
    TPyScriptThreadLocker(): m_state(PyGILState_Ensure() {}
    ~TPyScriptThreadLocker() { PyGILState_Release(m_state); }
</code></pre>

<p>run() function in thread object:</p>

<pre><code>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 );
</code></pre>

<p>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..</p>

<p>Python 2.7<br>
info from <a href="http://www.linuxjournal.com/article/3641?page=0,2" rel="nofollow">http://www.linuxjournal.com/article/3641?page=0,2</a></p>

<p>source: <a href="http://files.mail.ru/9D4TEF" rel="nofollow">http://files.mail.ru/9D4TEF</a>
pastebin: <a href="http://pastebin.com/DfFT9KN3" rel="nofollow">http://pastebin.com/DfFT9KN3</a></p>
