Skip to content

Instantly share code, notes, and snippets.

@snaewe
Last active December 14, 2015 08:09
Show Gist options
  • Save snaewe/5055988 to your computer and use it in GitHub Desktop.
Save snaewe/5055988 to your computer and use it in GitHub Desktop.
The correct way to initialize an embedded Python interpreter in a program that uses multiple threads.
// From http://wiki.blender.org/index.php/Dev:2.4/Source/Python/API/Threads
void start_python()
{
Py_NoSiteFlag = 1;
Py_SetProgramName("my_program_name");
Py_Initialize();
PyEval_InitThreads();
PyThreadState *py_tstate = PyGILState_GetThisThreadState();
PyEval_ReleaseThread(py_tstate);
}
void end_python()
{
PyGILState_Ensure();
Py_Finalize();
}
// RAII wrapper for Python GIL locking
struct gil_lock
{
public:
gil_lock()
:state(PyGILState_Ensure())
{
}
~gil_lock()
{
PyGILState_Release(state);
}
private:
PyGILState_STATE state;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment