title: Embedding Python in C++ crashes during running-time
body: <p>I've been around this question for way too long. Now I searched <a href="https://stackoverflow.com/questions/10625584/embedding-python-in-multithreaded-c-application?lq=1">this</a> and it was working for a while but it then crashed at a random place. I think that the problem is a deadlock or something.</p>
  
  <p>So please, someone tell me what I'm doing wrong:</p>
  
  <ol>
  <li><p>I make a global variable: </p>
  
  <pre><code>static int gil_init = 0; 
  </code></pre></li>
  <li><p>At the start of the program I call <code>Py_Initialize()</code>. This start function is called multiple times in one session but since <code>Py_Initialize()</code> is a non-op if Python is already initialized I don't think there's a problem here.</p></li>
  <li><p>From three functions I make lots of calls into the Python/C API function -<code>py_embed(...)</code> (there's only one at a time calling). The next code is present in the <code>py_embed()</code> function that is called from each thread:</p>
  
  <pre><code>if (!gil_init) {
      gil_init = 1;
      PyEval_InitThreads();
      PyEval_SaveThread();
  }
  state = PyGILState_Ensure();
  // Call Python/C API functions...
  //pValue= PyObject_CallObject(pFunc, pArgs2);  Crash is always given here
  PyGILState_Release(state);
  </code></pre></li>
  </ol>
  
  <p>Oh and the crash takes place in one of the functions, but not the first time I call it which is strange. That's why I said its at a random place during running time.</p>
  
  <p>In theory, and based in the reference manual of the <a href="https://docs.python.org/3.2/c-api/init.html#PyEval_InitThreads" rel="nofollow noreferrer">C Api</a> it should be working.. What am I doing wrong?</p>
  
  <p>Edit: I don't call <code>Py_Finalize()</code> because of <a href="https://stackoverflow.com/questions/7676314/py-initialize-py-finalize-not-working-twice-with-numpy">this problem</a> that I had</p>