Issue 5299: PyGILState_Ensure()/PyGILState_Release() documentation incomplete? (original) (raw)

The threading API documentation might omit out some important information about the GIL.

The GIL can be acquired by explicitly calling PyEval_AcquireLock(). One can also acquire the GIL by calling PyGILState_Ensure(). The latter differs from the former in that calling PyGILState_Ensure() when one already has the GIL will not create deadlock. This is implied; it would be helpful if this was explicitly stated.

Likewise, I assume that the Nth call to PyGILState_Release() releases the GIL, where N = the number of calls made previously to PyGILState_Ensure(). But I don't know this and the documentation doesn't make it clear.

As a first-time user of the API, it makes me nervous to call PyGILState_Ensure() which acquires the GIL without knowing for sure that PyGILState_Release() releases it. I can't evaluate my code for logical correctness, and when dealing with threads and the GIL, neither can I be sure that timing-dependent bugs will show up in testing. As a result, my code feels fragile.

I don't understand how the code works well enough to suggest better documentation. If nothing else, it would be useful to see something that promises that as long as each call to PyGILState_Ensure() is matched with a call to PyGILState_Release(), the GIL will take care of itself.