Embedded Python 3 - GIL Locking

The Python documentation does not adequately describe how to lock the GIL for embedded Python 3.x. After some trial and error and lots of searching, I was finally able to understand how the GIL should be locked. The GIL must be locked when any Python code/script is called otherwise you’ll end up with lots of access violations.

In your initialization function:

Py_Initialize();
PyEval_InitThreads();

// You must store this variable for later use (to be used when finalizing Python)
PyThreadState* main_thread = PyEval_SaveThread();

In any function that calls Python:

PyGILState_STATE gil_state = PyGILState_Ensure();

// Call Python code

PyGILState_Release(gil_state);

In your Python finalization function:

PyEval_RestoreThread(main_thread);
Py_Finalize();
Comments