diff -r de5f5648be2d Python/pystate.c --- a/Python/pystate.c Tue Mar 15 17:24:13 2016 +0100 +++ b/Python/pystate.c Tue Mar 15 17:56:04 2016 +0100 @@ -807,6 +807,8 @@ PyGILState_Ensure(void) { int current; PyThreadState *tcur; + int need_init_threads = 0; + /* Note that we do not auto-init Python here - apart from potential races with 2 threads auto-initializing, pep-311 spells out other issues. Embedders are expected to have @@ -815,10 +817,7 @@ PyGILState_Ensure(void) assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */ tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey); if (tcur == NULL) { - /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is - called from a new thread for the first time, we need the create the - GIL. */ - PyEval_InitThreads(); + need_init_threads = 1; /* Create a new thread state for this thread */ tcur = PyThreadState_New(autoInterpreterState); @@ -831,6 +830,7 @@ PyGILState_Ensure(void) } else current = PyThreadState_IsCurrent(tcur); + if (current == 0) PyEval_RestoreThread(tcur); /* Update our counter in the thread-state - no need for locks: @@ -839,6 +839,14 @@ PyGILState_Ensure(void) to modify this value */ ++tcur->gilstate_counter; + + if (need_init_threads) { + /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is + called from a new thread for the first time, we need the create the + GIL. */ + PyEval_InitThreads(); + } + return current ? PyGILState_LOCKED : PyGILState_UNLOCKED; }