title: Embedding python in multithreaded C application
body: <p>I'm embedding the python interpreter in a multithreaded C application and I'm a little confused as to what APIs I should use to ensure thread safety.</p>
  
  <p>From what I gathered, when embedding python it is up to the embedder to take care of the GIL lock before calling any other Python C API call. This is done with these functions:</p>
  
  <pre><code>gstate = PyGILState_Ensure();
  // do some python api calls, run python scripts
  PyGILState_Release(gstate);
  </code></pre>
  
  <p>But this alone doesn't seem to be enough. I still got random crashes since it doesn't seem to provide mutual exclusion for the Python APIs.</p>
  
  <p>After reading some more docs I also added: </p>
  
  <pre><code>PyEval_InitThreads();
  </code></pre>
  
  <p>right after the call to <code>Py_IsInitialized()</code> but that's where the confusing part comes. The docs state that this function:</p>
  
  <blockquote>
    <p>Initialize and acquire the global interpreter lock</p>
  </blockquote>
  
  <p>This suggests that when this function returns, the GIL is supposed to be locked and should be unlocked somehow. but in practice this doesn't seem to be required. With this line in place my multithreaded worked perfectly and mutual exclusion was maintained by the <code>PyGILState_Ensure/Release</code> functions.<br>
  When I tried adding <code>PyEval_ReleaseLock()</code> after <code>PyEval_ReleaseLock()</code> the app dead-locked pretty quickly in a subsequent call to <code>PyImport_ExecCodeModule()</code>.</p>
  
  <p>So what am I missing here? </p>