跳到主要内容

Initialization, Finalization, and Threads

Before Python Initialization

In an application embedding Python, the Py_Initialize() function must be called before using any other Python/C API functions; with the exception of a few functions and the global configuration variables

  • PyImport_AppendInittab() ......

Global configuration variables

Python has variables for the global configuration to control different features and options. By default, these flags are controlled by command line options

Initializing and finalizing the interpreter

  • void Py_Initialize()
  • void Py_InitializeEx(int initsigs)
  • int Py_IsInitialized()
  • int Py_FinalizeEx()
  • void Py_Finalize()

Process-wide parameters

  • wchar_t *Py_GetProgramName()
  • wchar_t *Py_GetProgramFullPath()
  • wchar_t *Py_GetPath(): The list sys.path is initialized with this value on interpreter startup; it can be (and usually is) modified later to change the search path for loading modules
  • const char *Py_GetVersion(): The value is available to Python code as sys.version
  • const char *Py_GetPlatform(): The value is available to Python code as sys.platform
  • const char *Py_GetCompiler()
  • const char *Py_GetBuildInfo()
  • wchar_t *Py_GetPythonHome()

Thread State and the Global Interpreter Lock

The lock is also released around potentially blocking I/O operations like reading or writing a file, so that other Python threads can run in the meantime.

The Python interpreter keeps some thread-specific bookkeeping information inside a data structure called PyThreadState. There’s also one global variable pointing to the current PyThreadState: it can be retrieved using PyThreadState_Get()

High-level API

  • PyThreadState *PyEval_SaveThread()
  • void PyEval_RestoreThread(PyThreadState *tstate)
  • PyThreadState *PyThreadState_Get()
  • PyGILState_STATE PyGILState_Ensure()
  • void PyGILState_Release(PyGILState_STATE)
  • int PyGILState_Check()

Low-level API

  • void PyEval_AcquireThread(PyThreadState *tstate)
  • void PyEval_ReleaseThread(PyThreadState *tstate)

Asynchronous Notifications

  • int Py_AddPendingCall(int (*func)(void*), void *arg)

Profiling and Tracing

  • typedef int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
  • void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
  • void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)

Thread Local Storage Support

The Python interpreter provides low-level support for thread-local storage (TLS) which wraps the underlying native TLS implementation to support the Python-level thread local storage API (threading.local)

  • type Py_tss_t

  • Py_tss_NEEDS_INIT

  • Py_tss_t *PyThread_tss_alloc()

  • void PyThread_tss_free(Py_tss_t *key)

  • int PyThread_tss_is_created(Py_tss_t *key)

  • int PyThread_tss_create(Py_tss_t *key)

  • void PyThread_tss_delete(Py_tss_t *key)

  • int PyThread_tss_set(Py_tss_t *key, void *value)

  • void *PyThread_tss_get(Py_tss_t *key)