GIL is a regular mutex. The cost of locking or unlocking an unidentified mutex is extremely low, not much more than the cost of changing a global variable. However, if you lock and unlock the disputed mutex very often, the cost of the mutex can become significant.
So this is usually not a good idea:
Py_BEGIN_ALLOW_THREADS a = 1 + 1; Py_END_ALLOW_THREADS
What happens here, you unlock the mutex, which you are trying to lock again immediately afterwards. If this is a gap between two large pieces of code, then it gives the other thread the ability to run. But if you have no problems with detailing the flows, just hold the lock.
So this is a good idea in this context:
very_long_computation_requires_gil(); Py_BEGIN_ALLOW_THREADS; a = a + i; Py_END_ALLOW_THREADS; very_long_computation_also_requires_gil();
In fact, it is impossible to make an educated guess without knowing the context, and it is often still difficult without testing.
source share