'Acquire the GIL. The generated code is safe even when no PyThreadState
has been allocated for this thread (for threads not initialized by
using the Python API). Additionally, the code generated by this method
may be called recursively.'

def put_ensure_gil(self, declare_gilstate=True, variable=None):

    self.globalstate.use_utility_code(UtilityCode.load_cached('ForceInitThreads', 'ModuleSetupCode.c'))
    if self.globalstate.directives['fast_gil']:
        self.globalstate.use_utility_code(UtilityCode.load_cached('FastGil', 'ModuleSetupCode.c'))
    else:
        self.globalstate.use_utility_code(UtilityCode.load_cached('NoFastGil', 'ModuleSetupCode.c'))
    self.putln('#ifdef    WITH_THREAD')
    if (not variable):
        variable = '__pyx_gilstate_save'
        if declare_gilstate:
            self.put('PyGILState_STATE    ')
    self.putln(('%s    =    __Pyx_PyGILState_Ensure();' % variable))
    self.putln('#endif')
