Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your understanding is correct: invoking <code>PyEval_InitThreads</code> does, among other things, acquire the GIL. In a correctly written Python/C application, this is not an issue because the GIL will be unlocked in time, either automatically or manually.</p> <p>If the main thread goes on to run Python code, there is nothing special to do, because Python interpreter will automatically relinquish the GIL after a number of instructions have been executed (allowing another thread to acquire it, which will relinquish it again, and so on). Additionally, whenever Python is about to invoke a blocking system call, e.g. to read from the network or write to a file, it will release the GIL around the call.</p> <p>The original version of this answer pretty much ended here. But there is one more thing to take into account: the <em>embedding</em> scenario.</p> <p>When embedding Python, the main thread often initializes Python and goes on to execute other, non-Python-related tasks. In that scenario there is nothing that will <em>automatically</em> release the GIL, so this must be done by the thread itself. That is in no way specific to the call that calls <code>PyEval_InitThreads</code>, it is expected of <a href="https://docs.python.org/2/c-api/init.html#releasing-the-gil-from-extension-code" rel="nofollow noreferrer">all Python/C code</a> invoked with the GIL acquired.</p> <p>For example, the <code>main()</code> might contain code like this:</p> <pre><code>Py_Initialize(); PyEval_InitThreads(); Py_BEGIN_ALLOW_THREADS ... call the non-Python part of the application here ... Py_END_ALLOW_THREADS Py_Finalize(); </code></pre> <p>If your code creates threads manually, they need to acquire the GIL before doing <em>anything</em> Python-related, even as simple as <code>Py_INCREF</code>. To do so, use <a href="https://docs.python.org/2/c-api/init.html#non-python-created-threads" rel="nofollow noreferrer">the following</a>:</p> <pre><code>// Acquire the GIL PyGILState_STATE gstate; gstate = PyGILState_Ensure(); ... call Python code here ... // Release the GIL. No Python API allowed beyond this point. PyGILState_Release(gstate); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload