PLearn 0.1
Public Member Functions | Public Attributes
PLearn::PythonGlobalInterpreterLock Class Reference

Ensure thread safety by managing the Python Global Interpreter Lock. More...

#include <PythonObjectWrapper.h>

Collaboration diagram for PLearn::PythonGlobalInterpreterLock:
Collaboration graph
[legend]

List of all members.

Public Member Functions

 PythonGlobalInterpreterLock ()
 ~PythonGlobalInterpreterLock ()

Public Attributes

PyGILState_STATE m_gilstate

Detailed Description

Ensure thread safety by managing the Python Global Interpreter Lock.

The Python interpreter is not fully reentrant and must be handled carefully in the presence of multi-threading. While this does not affect multi-threaded pure Python code (for which reentrancy is properly managed), it does affect extensions that are written in other languages. To this end, Python provides a Global Interpreter Lock (GIL) which must be acquired before calling any of its API within extension code and released afterwards.

This class provides a simple Resource-Acquisition-is-Initialization (RAII) idiom to manage the GIL. The idea is to construct a local variable of this class at the beginning of a scope which uses Python. The constructor acquires the lock, and the destructor automatically releases it. For example:

  void foo()
  {
      // Acquire the Python lock.  This blocks if another thread
      // already has the lock.
      PythonGlobalInterpreterLock gil;

      // Code which uses the Python C API comes here
      // ...
  }   // Destructor releases the lock, so nothing to do.

Definition at line 772 of file PythonObjectWrapper.h.


Constructor & Destructor Documentation

PLearn::PythonGlobalInterpreterLock::PythonGlobalInterpreterLock ( ) [inline]

Definition at line 775 of file PythonObjectWrapper.h.

        : m_gilstate(PyGILState_Ensure())
    { }
PLearn::PythonGlobalInterpreterLock::~PythonGlobalInterpreterLock ( ) [inline]

Definition at line 779 of file PythonObjectWrapper.h.

References m_gilstate.

    {
        PyGILState_Release(m_gilstate);
    }

Member Data Documentation

Definition at line 784 of file PythonObjectWrapper.h.

Referenced by ~PythonGlobalInterpreterLock().


The documentation for this class was generated from the following file:
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines