/Doc/c-api/init.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 1021 lines · 722 code · 299 blank · 0 comment · 0 complexity · ce1182933f37f1ebb04aa105aa698a79 MD5 · raw file

  1. .. highlightlang:: c
  2. .. _initialization:
  3. *****************************************
  4. Initialization, Finalization, and Threads
  5. *****************************************
  6. .. cfunction:: void Py_Initialize()
  7. .. index::
  8. single: Py_SetProgramName()
  9. single: PyEval_InitThreads()
  10. single: PyEval_ReleaseLock()
  11. single: PyEval_AcquireLock()
  12. single: modules (in module sys)
  13. single: path (in module sys)
  14. module: __builtin__
  15. module: __main__
  16. module: sys
  17. triple: module; search; path
  18. single: PySys_SetArgv()
  19. single: Py_Finalize()
  20. Initialize the Python interpreter. In an application embedding Python, this
  21. should be called before using any other Python/C API functions; with the
  22. exception of :cfunc:`Py_SetProgramName`, :cfunc:`PyEval_InitThreads`,
  23. :cfunc:`PyEval_ReleaseLock`, and :cfunc:`PyEval_AcquireLock`. This initializes
  24. the table of loaded modules (``sys.modules``), and creates the fundamental
  25. modules :mod:`__builtin__`, :mod:`__main__` and :mod:`sys`. It also initializes
  26. the module search path (``sys.path``). It does not set ``sys.argv``; use
  27. :cfunc:`PySys_SetArgv` for that. This is a no-op when called for a second time
  28. (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a
  29. fatal error if the initialization fails.
  30. .. cfunction:: void Py_InitializeEx(int initsigs)
  31. This function works like :cfunc:`Py_Initialize` if *initsigs* is 1. If
  32. *initsigs* is 0, it skips initialization registration of signal handlers, which
  33. might be useful when Python is embedded.
  34. .. versionadded:: 2.4
  35. .. cfunction:: int Py_IsInitialized()
  36. Return true (nonzero) when the Python interpreter has been initialized, false
  37. (zero) if not. After :cfunc:`Py_Finalize` is called, this returns false until
  38. :cfunc:`Py_Initialize` is called again.
  39. .. cfunction:: void Py_Finalize()
  40. Undo all initializations made by :cfunc:`Py_Initialize` and subsequent use of
  41. Python/C API functions, and destroy all sub-interpreters (see
  42. :cfunc:`Py_NewInterpreter` below) that were created and not yet destroyed since
  43. the last call to :cfunc:`Py_Initialize`. Ideally, this frees all memory
  44. allocated by the Python interpreter. This is a no-op when called for a second
  45. time (without calling :cfunc:`Py_Initialize` again first). There is no return
  46. value; errors during finalization are ignored.
  47. This function is provided for a number of reasons. An embedding application
  48. might want to restart Python without having to restart the application itself.
  49. An application that has loaded the Python interpreter from a dynamically
  50. loadable library (or DLL) might want to free all memory allocated by Python
  51. before unloading the DLL. During a hunt for memory leaks in an application a
  52. developer might want to free all memory allocated by Python before exiting from
  53. the application.
  54. **Bugs and caveats:** The destruction of modules and objects in modules is done
  55. in random order; this may cause destructors (:meth:`__del__` methods) to fail
  56. when they depend on other objects (even functions) or modules. Dynamically
  57. loaded extension modules loaded by Python are not unloaded. Small amounts of
  58. memory allocated by the Python interpreter may not be freed (if you find a leak,
  59. please report it). Memory tied up in circular references between objects is not
  60. freed. Some memory allocated by extension modules may not be freed. Some
  61. extensions may not work properly if their initialization routine is called more
  62. than once; this can happen if an application calls :cfunc:`Py_Initialize` and
  63. :cfunc:`Py_Finalize` more than once.
  64. .. cfunction:: PyThreadState* Py_NewInterpreter()
  65. .. index::
  66. module: __builtin__
  67. module: __main__
  68. module: sys
  69. single: stdout (in module sys)
  70. single: stderr (in module sys)
  71. single: stdin (in module sys)
  72. Create a new sub-interpreter. This is an (almost) totally separate environment
  73. for the execution of Python code. In particular, the new interpreter has
  74. separate, independent versions of all imported modules, including the
  75. fundamental modules :mod:`__builtin__`, :mod:`__main__` and :mod:`sys`. The
  76. table of loaded modules (``sys.modules``) and the module search path
  77. (``sys.path``) are also separate. The new environment has no ``sys.argv``
  78. variable. It has new standard I/O stream file objects ``sys.stdin``,
  79. ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
  80. :ctype:`FILE` structures in the C library).
  81. The return value points to the first thread state created in the new
  82. sub-interpreter. This thread state is made in the current thread state.
  83. Note that no actual thread is created; see the discussion of thread states
  84. below. If creation of the new interpreter is unsuccessful, *NULL* is
  85. returned; no exception is set since the exception state is stored in the
  86. current thread state and there may not be a current thread state. (Like all
  87. other Python/C API functions, the global interpreter lock must be held before
  88. calling this function and is still held when it returns; however, unlike most
  89. other Python/C API functions, there needn't be a current thread state on
  90. entry.)
  91. .. index::
  92. single: Py_Finalize()
  93. single: Py_Initialize()
  94. Extension modules are shared between (sub-)interpreters as follows: the first
  95. time a particular extension is imported, it is initialized normally, and a
  96. (shallow) copy of its module's dictionary is squirreled away. When the same
  97. extension is imported by another (sub-)interpreter, a new module is initialized
  98. and filled with the contents of this copy; the extension's ``init`` function is
  99. not called. Note that this is different from what happens when an extension is
  100. imported after the interpreter has been completely re-initialized by calling
  101. :cfunc:`Py_Finalize` and :cfunc:`Py_Initialize`; in that case, the extension's
  102. ``initmodule`` function *is* called again.
  103. .. index:: single: close() (in module os)
  104. **Bugs and caveats:** Because sub-interpreters (and the main interpreter) are
  105. part of the same process, the insulation between them isn't perfect --- for
  106. example, using low-level file operations like :func:`os.close` they can
  107. (accidentally or maliciously) affect each other's open files. Because of the
  108. way extensions are shared between (sub-)interpreters, some extensions may not
  109. work properly; this is especially likely when the extension makes use of
  110. (static) global variables, or when the extension manipulates its module's
  111. dictionary after its initialization. It is possible to insert objects created
  112. in one sub-interpreter into a namespace of another sub-interpreter; this should
  113. be done with great care to avoid sharing user-defined functions, methods,
  114. instances or classes between sub-interpreters, since import operations executed
  115. by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
  116. modules. (XXX This is a hard-to-fix bug that will be addressed in a future
  117. release.)
  118. Also note that the use of this functionality is incompatible with extension
  119. modules such as PyObjC and ctypes that use the :cfunc:`PyGILState_\*` APIs (and
  120. this is inherent in the way the :cfunc:`PyGILState_\*` functions work). Simple
  121. things may work, but confusing behavior will always be near.
  122. .. cfunction:: void Py_EndInterpreter(PyThreadState *tstate)
  123. .. index:: single: Py_Finalize()
  124. Destroy the (sub-)interpreter represented by the given thread state. The given
  125. thread state must be the current thread state. See the discussion of thread
  126. states below. When the call returns, the current thread state is *NULL*. All
  127. thread states associated with this interpreter are destroyed. (The global
  128. interpreter lock must be held before calling this function and is still held
  129. when it returns.) :cfunc:`Py_Finalize` will destroy all sub-interpreters that
  130. haven't been explicitly destroyed at that point.
  131. .. cfunction:: void Py_SetProgramName(char *name)
  132. .. index::
  133. single: Py_Initialize()
  134. single: main()
  135. single: Py_GetPath()
  136. This function should be called before :cfunc:`Py_Initialize` is called for
  137. the first time, if it is called at all. It tells the interpreter the value
  138. of the ``argv[0]`` argument to the :cfunc:`main` function of the program.
  139. This is used by :cfunc:`Py_GetPath` and some other functions below to find
  140. the Python run-time libraries relative to the interpreter executable. The
  141. default value is ``'python'``. The argument should point to a
  142. zero-terminated character string in static storage whose contents will not
  143. change for the duration of the program's execution. No code in the Python
  144. interpreter will change the contents of this storage.
  145. .. cfunction:: char* Py_GetProgramName()
  146. .. index:: single: Py_SetProgramName()
  147. Return the program name set with :cfunc:`Py_SetProgramName`, or the default.
  148. The returned string points into static storage; the caller should not modify its
  149. value.
  150. .. cfunction:: char* Py_GetPrefix()
  151. Return the *prefix* for installed platform-independent files. This is derived
  152. through a number of complicated rules from the program name set with
  153. :cfunc:`Py_SetProgramName` and some environment variables; for example, if the
  154. program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
  155. returned string points into static storage; the caller should not modify its
  156. value. This corresponds to the :makevar:`prefix` variable in the top-level
  157. :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure`
  158. script at build time. The value is available to Python code as ``sys.prefix``.
  159. It is only useful on Unix. See also the next function.
  160. .. cfunction:: char* Py_GetExecPrefix()
  161. Return the *exec-prefix* for installed platform-*dependent* files. This is
  162. derived through a number of complicated rules from the program name set with
  163. :cfunc:`Py_SetProgramName` and some environment variables; for example, if the
  164. program name is ``'/usr/local/bin/python'``, the exec-prefix is
  165. ``'/usr/local'``. The returned string points into static storage; the caller
  166. should not modify its value. This corresponds to the :makevar:`exec_prefix`
  167. variable in the top-level :file:`Makefile` and the :option:`--exec-prefix`
  168. argument to the :program:`configure` script at build time. The value is
  169. available to Python code as ``sys.exec_prefix``. It is only useful on Unix.
  170. Background: The exec-prefix differs from the prefix when platform dependent
  171. files (such as executables and shared libraries) are installed in a different
  172. directory tree. In a typical installation, platform dependent files may be
  173. installed in the :file:`/usr/local/plat` subtree while platform independent may
  174. be installed in :file:`/usr/local`.
  175. Generally speaking, a platform is a combination of hardware and software
  176. families, e.g. Sparc machines running the Solaris 2.x operating system are
  177. considered the same platform, but Intel machines running Solaris 2.x are another
  178. platform, and Intel machines running Linux are yet another platform. Different
  179. major revisions of the same operating system generally also form different
  180. platforms. Non-Unix operating systems are a different story; the installation
  181. strategies on those systems are so different that the prefix and exec-prefix are
  182. meaningless, and set to the empty string. Note that compiled Python bytecode
  183. files are platform independent (but not independent from the Python version by
  184. which they were compiled!).
  185. System administrators will know how to configure the :program:`mount` or
  186. :program:`automount` programs to share :file:`/usr/local` between platforms
  187. while having :file:`/usr/local/plat` be a different filesystem for each
  188. platform.
  189. .. cfunction:: char* Py_GetProgramFullPath()
  190. .. index::
  191. single: Py_SetProgramName()
  192. single: executable (in module sys)
  193. Return the full program name of the Python executable; this is computed as a
  194. side-effect of deriving the default module search path from the program name
  195. (set by :cfunc:`Py_SetProgramName` above). The returned string points into
  196. static storage; the caller should not modify its value. The value is available
  197. to Python code as ``sys.executable``.
  198. .. cfunction:: char* Py_GetPath()
  199. .. index::
  200. triple: module; search; path
  201. single: path (in module sys)
  202. Return the default module search path; this is computed from the program name
  203. (set by :cfunc:`Py_SetProgramName` above) and some environment variables. The
  204. returned string consists of a series of directory names separated by a platform
  205. dependent delimiter character. The delimiter character is ``':'`` on Unix and
  206. Mac OS X, ``';'`` on Windows. The returned string points into static storage;
  207. the caller should not modify its value. The value is available to Python code
  208. as the list ``sys.path``, which may be modified to change the future search path
  209. for loaded modules.
  210. .. XXX should give the exact rules
  211. .. cfunction:: const char* Py_GetVersion()
  212. Return the version of this Python interpreter. This is a string that looks
  213. something like ::
  214. "1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
  215. .. index:: single: version (in module sys)
  216. The first word (up to the first space character) is the current Python version;
  217. the first three characters are the major and minor version separated by a
  218. period. The returned string points into static storage; the caller should not
  219. modify its value. The value is available to Python code as ``sys.version``.
  220. .. cfunction:: const char* Py_GetBuildNumber()
  221. Return a string representing the Subversion revision that this Python executable
  222. was built from. This number is a string because it may contain a trailing 'M'
  223. if Python was built from a mixed revision source tree.
  224. .. versionadded:: 2.5
  225. .. cfunction:: const char* Py_GetPlatform()
  226. .. index:: single: platform (in module sys)
  227. Return the platform identifier for the current platform. On Unix, this is
  228. formed from the "official" name of the operating system, converted to lower
  229. case, followed by the major revision number; e.g., for Solaris 2.x, which is
  230. also known as SunOS 5.x, the value is ``'sunos5'``. On Mac OS X, it is
  231. ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
  232. static storage; the caller should not modify its value. The value is available
  233. to Python code as ``sys.platform``.
  234. .. cfunction:: const char* Py_GetCopyright()
  235. Return the official copyright string for the current Python version, for example
  236. ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
  237. .. index:: single: copyright (in module sys)
  238. The returned string points into static storage; the caller should not modify its
  239. value. The value is available to Python code as ``sys.copyright``.
  240. .. cfunction:: const char* Py_GetCompiler()
  241. Return an indication of the compiler used to build the current Python version,
  242. in square brackets, for example::
  243. "[GCC 2.7.2.2]"
  244. .. index:: single: version (in module sys)
  245. The returned string points into static storage; the caller should not modify its
  246. value. The value is available to Python code as part of the variable
  247. ``sys.version``.
  248. .. cfunction:: const char* Py_GetBuildInfo()
  249. Return information about the sequence number and build date and time of the
  250. current Python interpreter instance, for example ::
  251. "#67, Aug 1 1997, 22:34:28"
  252. .. index:: single: version (in module sys)
  253. The returned string points into static storage; the caller should not modify its
  254. value. The value is available to Python code as part of the variable
  255. ``sys.version``.
  256. .. cfunction:: void PySys_SetArgv(int argc, char **argv)
  257. .. index::
  258. single: main()
  259. single: Py_FatalError()
  260. single: argv (in module sys)
  261. Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
  262. similar to those passed to the program's :cfunc:`main` function with the
  263. difference that the first entry should refer to the script file to be
  264. executed rather than the executable hosting the Python interpreter. If there
  265. isn't a script that will be run, the first entry in *argv* can be an empty
  266. string. If this function fails to initialize :data:`sys.argv`, a fatal
  267. condition is signalled using :cfunc:`Py_FatalError`.
  268. This function also prepends the executed script's path to :data:`sys.path`.
  269. If no script is executed (in the case of calling ``python -c`` or just the
  270. interactive interpreter), the empty string is used instead.
  271. .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
  272. check w/ Guido.
  273. .. cfunction:: void Py_SetPythonHome(char *home)
  274. Set the default "home" directory, that is, the location of the standard
  275. Python libraries. The libraries are searched in
  276. :file:`{home}/lib/python{version}` and :file:`{home}/lib/python{version}`.
  277. The argument should point to a zero-terminated character string in static
  278. storage whose contents will not change for the duration of the program's
  279. execution. No code in the Python interpreter will change the contents of
  280. this storage.
  281. .. cfunction:: char* Py_GetPythonHome()
  282. Return the default "home", that is, the value set by a previous call to
  283. :cfunc:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
  284. environment variable if it is set.
  285. .. _threads:
  286. Thread State and the Global Interpreter Lock
  287. ============================================
  288. .. index::
  289. single: global interpreter lock
  290. single: interpreter lock
  291. single: lock, interpreter
  292. The Python interpreter is not fully thread safe. In order to support
  293. multi-threaded Python programs, there's a global lock, called the :dfn:`global
  294. interpreter lock` or :dfn:`GIL`, that must be held by the current thread before
  295. it can safely access Python objects. Without the lock, even the simplest
  296. operations could cause problems in a multi-threaded program: for example, when
  297. two threads simultaneously increment the reference count of the same object, the
  298. reference count could end up being incremented only once instead of twice.
  299. .. index:: single: setcheckinterval() (in module sys)
  300. Therefore, the rule exists that only the thread that has acquired the global
  301. interpreter lock may operate on Python objects or call Python/C API functions.
  302. In order to support multi-threaded Python programs, the interpreter regularly
  303. releases and reacquires the lock --- by default, every 100 bytecode instructions
  304. (this can be changed with :func:`sys.setcheckinterval`). The lock is also
  305. released and reacquired around potentially blocking I/O operations like reading
  306. or writing a file, so that other threads can run while the thread that requests
  307. the I/O is waiting for the I/O operation to complete.
  308. .. index::
  309. single: PyThreadState
  310. single: PyThreadState
  311. The Python interpreter needs to keep some bookkeeping information separate per
  312. thread --- for this it uses a data structure called :ctype:`PyThreadState`.
  313. There's one global variable, however: the pointer to the current
  314. :ctype:`PyThreadState` structure. Before the addition of :dfn:`thread-local
  315. storage` (:dfn:`TLS`) the current thread state had to be manipulated
  316. explicitly.
  317. This is easy enough in most cases. Most code manipulating the global
  318. interpreter lock has the following simple structure::
  319. Save the thread state in a local variable.
  320. Release the global interpreter lock.
  321. ...Do some blocking I/O operation...
  322. Reacquire the global interpreter lock.
  323. Restore the thread state from the local variable.
  324. This is so common that a pair of macros exists to simplify it::
  325. Py_BEGIN_ALLOW_THREADS
  326. ...Do some blocking I/O operation...
  327. Py_END_ALLOW_THREADS
  328. .. index::
  329. single: Py_BEGIN_ALLOW_THREADS
  330. single: Py_END_ALLOW_THREADS
  331. The :cmacro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
  332. hidden local variable; the :cmacro:`Py_END_ALLOW_THREADS` macro closes the
  333. block. Another advantage of using these two macros is that when Python is
  334. compiled without thread support, they are defined empty, thus saving the thread
  335. state and GIL manipulations.
  336. When thread support is enabled, the block above expands to the following code::
  337. PyThreadState *_save;
  338. _save = PyEval_SaveThread();
  339. ...Do some blocking I/O operation...
  340. PyEval_RestoreThread(_save);
  341. Using even lower level primitives, we can get roughly the same effect as
  342. follows::
  343. PyThreadState *_save;
  344. _save = PyThreadState_Swap(NULL);
  345. PyEval_ReleaseLock();
  346. ...Do some blocking I/O operation...
  347. PyEval_AcquireLock();
  348. PyThreadState_Swap(_save);
  349. .. index::
  350. single: PyEval_RestoreThread()
  351. single: errno
  352. single: PyEval_SaveThread()
  353. single: PyEval_ReleaseLock()
  354. single: PyEval_AcquireLock()
  355. There are some subtle differences; in particular, :cfunc:`PyEval_RestoreThread`
  356. saves and restores the value of the global variable :cdata:`errno`, since the
  357. lock manipulation does not guarantee that :cdata:`errno` is left alone. Also,
  358. when thread support is disabled, :cfunc:`PyEval_SaveThread` and
  359. :cfunc:`PyEval_RestoreThread` don't manipulate the GIL; in this case,
  360. :cfunc:`PyEval_ReleaseLock` and :cfunc:`PyEval_AcquireLock` are not available.
  361. This is done so that dynamically loaded extensions compiled with thread support
  362. enabled can be loaded by an interpreter that was compiled with disabled thread
  363. support.
  364. The global interpreter lock is used to protect the pointer to the current thread
  365. state. When releasing the lock and saving the thread state, the current thread
  366. state pointer must be retrieved before the lock is released (since another
  367. thread could immediately acquire the lock and store its own thread state in the
  368. global variable). Conversely, when acquiring the lock and restoring the thread
  369. state, the lock must be acquired before storing the thread state pointer.
  370. It is important to note that when threads are created from C, they don't have
  371. the global interpreter lock, nor is there a thread state data structure for
  372. them. Such threads must bootstrap themselves into existence, by first
  373. creating a thread state data structure, then acquiring the lock, and finally
  374. storing their thread state pointer, before they can start using the Python/C
  375. API. When they are done, they should reset the thread state pointer, release
  376. the lock, and finally free their thread state data structure.
  377. Beginning with version 2.3, threads can now take advantage of the
  378. :cfunc:`PyGILState_\*` functions to do all of the above automatically. The
  379. typical idiom for calling into Python from a C thread is now::
  380. PyGILState_STATE gstate;
  381. gstate = PyGILState_Ensure();
  382. /* Perform Python actions here. */
  383. result = CallSomeFunction();
  384. /* evaluate result */
  385. /* Release the thread. No Python API allowed beyond this point. */
  386. PyGILState_Release(gstate);
  387. Note that the :cfunc:`PyGILState_\*` functions assume there is only one global
  388. interpreter (created automatically by :cfunc:`Py_Initialize`). Python still
  389. supports the creation of additional interpreters (using
  390. :cfunc:`Py_NewInterpreter`), but mixing multiple interpreters and the
  391. :cfunc:`PyGILState_\*` API is unsupported.
  392. Another important thing to note about threads is their behaviour in the face
  393. of the C :cfunc:`fork` call. On most systems with :cfunc:`fork`, after a
  394. process forks only the thread that issued the fork will exist. That also
  395. means any locks held by other threads will never be released. Python solves
  396. this for :func:`os.fork` by acquiring the locks it uses internally before
  397. the fork, and releasing them afterwards. In addition, it resets any
  398. :ref:`lock-objects` in the child. When extending or embedding Python, there
  399. is no way to inform Python of additional (non-Python) locks that need to be
  400. acquired before or reset after a fork. OS facilities such as
  401. :cfunc:`posix_atfork` would need to be used to accomplish the same thing.
  402. Additionally, when extending or embedding Python, calling :cfunc:`fork`
  403. directly rather than through :func:`os.fork` (and returning to or calling
  404. into Python) may result in a deadlock by one of Python's internal locks
  405. being held by a thread that is defunct after the fork.
  406. :cfunc:`PyOS_AfterFork` tries to reset the necessary locks, but is not
  407. always able to.
  408. .. ctype:: PyInterpreterState
  409. This data structure represents the state shared by a number of cooperating
  410. threads. Threads belonging to the same interpreter share their module
  411. administration and a few other internal items. There are no public members in
  412. this structure.
  413. Threads belonging to different interpreters initially share nothing, except
  414. process state like available memory, open file descriptors and such. The global
  415. interpreter lock is also shared by all threads, regardless of to which
  416. interpreter they belong.
  417. .. ctype:: PyThreadState
  418. This data structure represents the state of a single thread. The only public
  419. data member is :ctype:`PyInterpreterState \*`:attr:`interp`, which points to
  420. this thread's interpreter state.
  421. .. cfunction:: void PyEval_InitThreads()
  422. .. index::
  423. single: PyEval_ReleaseLock()
  424. single: PyEval_ReleaseThread()
  425. single: PyEval_SaveThread()
  426. single: PyEval_RestoreThread()
  427. Initialize and acquire the global interpreter lock. It should be called in the
  428. main thread before creating a second thread or engaging in any other thread
  429. operations such as :cfunc:`PyEval_ReleaseLock` or
  430. ``PyEval_ReleaseThread(tstate)``. It is not needed before calling
  431. :cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_RestoreThread`.
  432. .. index:: single: Py_Initialize()
  433. This is a no-op when called for a second time. It is safe to call this function
  434. before calling :cfunc:`Py_Initialize`.
  435. .. index:: module: thread
  436. When only the main thread exists, no GIL operations are needed. This is a
  437. common situation (most Python programs do not use threads), and the lock
  438. operations slow the interpreter down a bit. Therefore, the lock is not
  439. created initially. This situation is equivalent to having acquired the lock:
  440. when there is only a single thread, all object accesses are safe. Therefore,
  441. when this function initializes the global interpreter lock, it also acquires
  442. it. Before the Python :mod:`thread` module creates a new thread, knowing
  443. that either it has the lock or the lock hasn't been created yet, it calls
  444. :cfunc:`PyEval_InitThreads`. When this call returns, it is guaranteed that
  445. the lock has been created and that the calling thread has acquired it.
  446. It is **not** safe to call this function when it is unknown which thread (if
  447. any) currently has the global interpreter lock.
  448. This function is not available when thread support is disabled at compile time.
  449. .. cfunction:: int PyEval_ThreadsInitialized()
  450. Returns a non-zero value if :cfunc:`PyEval_InitThreads` has been called. This
  451. function can be called without holding the GIL, and therefore can be used to
  452. avoid calls to the locking API when running single-threaded. This function is
  453. not available when thread support is disabled at compile time.
  454. .. versionadded:: 2.4
  455. .. cfunction:: void PyEval_AcquireLock()
  456. Acquire the global interpreter lock. The lock must have been created earlier.
  457. If this thread already has the lock, a deadlock ensues. This function is not
  458. available when thread support is disabled at compile time.
  459. .. cfunction:: void PyEval_ReleaseLock()
  460. Release the global interpreter lock. The lock must have been created earlier.
  461. This function is not available when thread support is disabled at compile time.
  462. .. cfunction:: void PyEval_AcquireThread(PyThreadState *tstate)
  463. Acquire the global interpreter lock and set the current thread state to
  464. *tstate*, which should not be *NULL*. The lock must have been created earlier.
  465. If this thread already has the lock, deadlock ensues. This function is not
  466. available when thread support is disabled at compile time.
  467. .. cfunction:: void PyEval_ReleaseThread(PyThreadState *tstate)
  468. Reset the current thread state to *NULL* and release the global interpreter
  469. lock. The lock must have been created earlier and must be held by the current
  470. thread. The *tstate* argument, which must not be *NULL*, is only used to check
  471. that it represents the current thread state --- if it isn't, a fatal error is
  472. reported. This function is not available when thread support is disabled at
  473. compile time.
  474. .. cfunction:: PyThreadState* PyEval_SaveThread()
  475. Release the global interpreter lock (if it has been created and thread
  476. support is enabled) and reset the thread state to *NULL*, returning the
  477. previous thread state (which is not *NULL*). If the lock has been created,
  478. the current thread must have acquired it. (This function is available even
  479. when thread support is disabled at compile time.)
  480. .. cfunction:: void PyEval_RestoreThread(PyThreadState *tstate)
  481. Acquire the global interpreter lock (if it has been created and thread
  482. support is enabled) and set the thread state to *tstate*, which must not be
  483. *NULL*. If the lock has been created, the current thread must not have
  484. acquired it, otherwise deadlock ensues. (This function is available even
  485. when thread support is disabled at compile time.)
  486. .. cfunction:: void PyEval_ReInitThreads()
  487. This function is called from :cfunc:`PyOS_AfterFork` to ensure that newly
  488. created child processes don't hold locks referring to threads which
  489. are not running in the child process.
  490. The following macros are normally used without a trailing semicolon; look for
  491. example usage in the Python source distribution.
  492. .. cmacro:: Py_BEGIN_ALLOW_THREADS
  493. This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
  494. Note that it contains an opening brace; it must be matched with a following
  495. :cmacro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
  496. macro. It is a no-op when thread support is disabled at compile time.
  497. .. cmacro:: Py_END_ALLOW_THREADS
  498. This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
  499. a closing brace; it must be matched with an earlier
  500. :cmacro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
  501. this macro. It is a no-op when thread support is disabled at compile time.
  502. .. cmacro:: Py_BLOCK_THREADS
  503. This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
  504. :cmacro:`Py_END_ALLOW_THREADS` without the closing brace. It is a no-op when
  505. thread support is disabled at compile time.
  506. .. cmacro:: Py_UNBLOCK_THREADS
  507. This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
  508. :cmacro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
  509. declaration. It is a no-op when thread support is disabled at compile time.
  510. All of the following functions are only available when thread support is enabled
  511. at compile time, and must be called only when the global interpreter lock has
  512. been created.
  513. .. cfunction:: PyInterpreterState* PyInterpreterState_New()
  514. Create a new interpreter state object. The global interpreter lock need not
  515. be held, but may be held if it is necessary to serialize calls to this
  516. function.
  517. .. cfunction:: void PyInterpreterState_Clear(PyInterpreterState *interp)
  518. Reset all information in an interpreter state object. The global interpreter
  519. lock must be held.
  520. .. cfunction:: void PyInterpreterState_Delete(PyInterpreterState *interp)
  521. Destroy an interpreter state object. The global interpreter lock need not be
  522. held. The interpreter state must have been reset with a previous call to
  523. :cfunc:`PyInterpreterState_Clear`.
  524. .. cfunction:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
  525. Create a new thread state object belonging to the given interpreter object.
  526. The global interpreter lock need not be held, but may be held if it is
  527. necessary to serialize calls to this function.
  528. .. cfunction:: void PyThreadState_Clear(PyThreadState *tstate)
  529. Reset all information in a thread state object. The global interpreter lock
  530. must be held.
  531. .. cfunction:: void PyThreadState_Delete(PyThreadState *tstate)
  532. Destroy a thread state object. The global interpreter lock need not be held.
  533. The thread state must have been reset with a previous call to
  534. :cfunc:`PyThreadState_Clear`.
  535. .. cfunction:: PyThreadState* PyThreadState_Get()
  536. Return the current thread state. The global interpreter lock must be held.
  537. When the current thread state is *NULL*, this issues a fatal error (so that
  538. the caller needn't check for *NULL*).
  539. .. cfunction:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
  540. Swap the current thread state with the thread state given by the argument
  541. *tstate*, which may be *NULL*. The global interpreter lock must be held.
  542. .. cfunction:: PyObject* PyThreadState_GetDict()
  543. Return a dictionary in which extensions can store thread-specific state
  544. information. Each extension should use a unique key to use to store state in
  545. the dictionary. It is okay to call this function when no current thread state
  546. is available. If this function returns *NULL*, no exception has been raised and
  547. the caller should assume no current thread state is available.
  548. .. versionchanged:: 2.3
  549. Previously this could only be called when a current thread is active, and *NULL*
  550. meant that an exception was raised.
  551. .. cfunction:: int PyThreadState_SetAsyncExc(long id, PyObject *exc)
  552. Asynchronously raise an exception in a thread. The *id* argument is the thread
  553. id of the target thread; *exc* is the exception object to be raised. This
  554. function does not steal any references to *exc*. To prevent naive misuse, you
  555. must write your own C extension to call this. Must be called with the GIL held.
  556. Returns the number of thread states modified; this is normally one, but will be
  557. zero if the thread id isn't found. If *exc* is :const:`NULL`, the pending
  558. exception (if any) for the thread is cleared. This raises no exceptions.
  559. .. versionadded:: 2.3
  560. .. cfunction:: PyGILState_STATE PyGILState_Ensure()
  561. Ensure that the current thread is ready to call the Python C API regardless
  562. of the current state of Python, or of the global interpreter lock. This may
  563. be called as many times as desired by a thread as long as each call is
  564. matched with a call to :cfunc:`PyGILState_Release`. In general, other
  565. thread-related APIs may be used between :cfunc:`PyGILState_Ensure` and
  566. :cfunc:`PyGILState_Release` calls as long as the thread state is restored to
  567. its previous state before the Release(). For example, normal usage of the
  568. :cmacro:`Py_BEGIN_ALLOW_THREADS` and :cmacro:`Py_END_ALLOW_THREADS` macros is
  569. acceptable.
  570. The return value is an opaque "handle" to the thread state when
  571. :cfunc:`PyGILState_Ensure` was called, and must be passed to
  572. :cfunc:`PyGILState_Release` to ensure Python is left in the same state. Even
  573. though recursive calls are allowed, these handles *cannot* be shared - each
  574. unique call to :cfunc:`PyGILState_Ensure` must save the handle for its call
  575. to :cfunc:`PyGILState_Release`.
  576. When the function returns, the current thread will hold the GIL. Failure is a
  577. fatal error.
  578. .. versionadded:: 2.3
  579. .. cfunction:: void PyGILState_Release(PyGILState_STATE)
  580. Release any resources previously acquired. After this call, Python's state will
  581. be the same as it was prior to the corresponding :cfunc:`PyGILState_Ensure` call
  582. (but generally this state will be unknown to the caller, hence the use of the
  583. GILState API.)
  584. Every call to :cfunc:`PyGILState_Ensure` must be matched by a call to
  585. :cfunc:`PyGILState_Release` on the same thread.
  586. .. versionadded:: 2.3
  587. .. _profiling:
  588. Profiling and Tracing
  589. =====================
  590. .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
  591. The Python interpreter provides some low-level support for attaching profiling
  592. and execution tracing facilities. These are used for profiling, debugging, and
  593. coverage analysis tools.
  594. Starting with Python 2.2, the implementation of this facility was substantially
  595. revised, and an interface from C was added. This C interface allows the
  596. profiling or tracing code to avoid the overhead of calling through Python-level
  597. callable objects, making a direct C function call instead. The essential
  598. attributes of the facility have not changed; the interface allows trace
  599. functions to be installed per-thread, and the basic events reported to the trace
  600. function are the same as had been reported to the Python-level trace functions
  601. in previous versions.
  602. .. ctype:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
  603. The type of the trace function registered using :cfunc:`PyEval_SetProfile` and
  604. :cfunc:`PyEval_SetTrace`. The first parameter is the object passed to the
  605. registration function as *obj*, *frame* is the frame object to which the event
  606. pertains, *what* is one of the constants :const:`PyTrace_CALL`,
  607. :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`,
  608. :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, or
  609. :const:`PyTrace_C_RETURN`, and *arg* depends on the value of *what*:
  610. +------------------------------+--------------------------------------+
  611. | Value of *what* | Meaning of *arg* |
  612. +==============================+======================================+
  613. | :const:`PyTrace_CALL` | Always *NULL*. |
  614. +------------------------------+--------------------------------------+
  615. | :const:`PyTrace_EXCEPTION` | Exception information as returned by |
  616. | | :func:`sys.exc_info`. |
  617. +------------------------------+--------------------------------------+
  618. | :const:`PyTrace_LINE` | Always *NULL*. |
  619. +------------------------------+--------------------------------------+
  620. | :const:`PyTrace_RETURN` | Value being returned to the caller. |
  621. +------------------------------+--------------------------------------+
  622. | :const:`PyTrace_C_CALL` | Name of function being called. |
  623. +------------------------------+--------------------------------------+
  624. | :const:`PyTrace_C_EXCEPTION` | Always *NULL*. |
  625. +------------------------------+--------------------------------------+
  626. | :const:`PyTrace_C_RETURN` | Always *NULL*. |
  627. +------------------------------+--------------------------------------+
  628. .. cvar:: int PyTrace_CALL
  629. The value of the *what* parameter to a :ctype:`Py_tracefunc` function when a new
  630. call to a function or method is being reported, or a new entry into a generator.
  631. Note that the creation of the iterator for a generator function is not reported
  632. as there is no control transfer to the Python bytecode in the corresponding
  633. frame.
  634. .. cvar:: int PyTrace_EXCEPTION
  635. The value of the *what* parameter to a :ctype:`Py_tracefunc` function when an
  636. exception has been raised. The callback function is called with this value for
  637. *what* when after any bytecode is processed after which the exception becomes
  638. set within the frame being executed. The effect of this is that as exception
  639. propagation causes the Python stack to unwind, the callback is called upon
  640. return to each frame as the exception propagates. Only trace functions receives
  641. these events; they are not needed by the profiler.
  642. .. cvar:: int PyTrace_LINE
  643. The value passed as the *what* parameter to a trace function (but not a
  644. profiling function) when a line-number event is being reported.
  645. .. cvar:: int PyTrace_RETURN
  646. The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a
  647. call is returning without propagating an exception.
  648. .. cvar:: int PyTrace_C_CALL
  649. The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
  650. function is about to be called.
  651. .. cvar:: int PyTrace_C_EXCEPTION
  652. The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
  653. function has thrown an exception.
  654. .. cvar:: int PyTrace_C_RETURN
  655. The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
  656. function has returned.
  657. .. cfunction:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
  658. Set the profiler function to *func*. The *obj* parameter is passed to the
  659. function as its first parameter, and may be any Python object, or *NULL*. If
  660. the profile function needs to maintain state, using a different value for *obj*
  661. for each thread provides a convenient and thread-safe place to store it. The
  662. profile function is called for all monitored events except the line-number
  663. events.
  664. .. cfunction:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
  665. Set the tracing function to *func*. This is similar to
  666. :cfunc:`PyEval_SetProfile`, except the tracing function does receive line-number
  667. events.
  668. .. cfunction:: PyObject* PyEval_GetCallStats(PyObject *self)
  669. Return a tuple of function call counts. There are constants defined for the
  670. positions within the tuple:
  671. +-------------------------------+-------+
  672. | Name | Value |
  673. +===============================+=======+
  674. | :const:`PCALL_ALL` | 0 |
  675. +-------------------------------+-------+
  676. | :const:`PCALL_FUNCTION` | 1 |
  677. +-------------------------------+-------+
  678. | :const:`PCALL_FAST_FUNCTION` | 2 |
  679. +-------------------------------+-------+
  680. | :const:`PCALL_FASTER_FUNCTION`| 3 |
  681. +-------------------------------+-------+
  682. | :const:`PCALL_METHOD` | 4 |
  683. +-------------------------------+-------+
  684. | :const:`PCALL_BOUND_METHOD` | 5 |
  685. +-------------------------------+-------+
  686. | :const:`PCALL_CFUNCTION` | 6 |
  687. +-------------------------------+-------+
  688. | :const:`PCALL_TYPE` | 7 |
  689. +-------------------------------+-------+
  690. | :const:`PCALL_GENERATOR` | 8 |
  691. +-------------------------------+-------+
  692. | :const:`PCALL_OTHER` | 9 |
  693. +-------------------------------+-------+
  694. | :const:`PCALL_POP` | 10 |
  695. +-------------------------------+-------+
  696. :const:`PCALL_FAST_FUNCTION` means no argument tuple needs to be created.
  697. :const:`PCALL_FASTER_FUNCTION` means that the fast-path frame setup code is used.
  698. If there is a method call where the call can be optimized by changing
  699. the argument tuple and calling the function directly, it gets recorded
  700. twice.
  701. This function is only present if Python is compiled with :const:`CALL_PROFILE`
  702. defined.
  703. .. _advanced-debugging:
  704. Advanced Debugger Support
  705. =========================
  706. .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
  707. These functions are only intended to be used by advanced debugging tools.
  708. .. cfunction:: PyInterpreterState* PyInterpreterState_Head()
  709. Return the interpreter state object at the head of the list of all such objects.
  710. .. versionadded:: 2.2
  711. .. cfunction:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
  712. Return the next interpreter state object after *interp* from the list of all
  713. such objects.
  714. .. versionadded:: 2.2
  715. .. cfunction:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
  716. Return the a pointer to the first :ctype:`PyThreadState` object in the list of
  717. threads associated with the interpreter *interp*.
  718. .. versionadded:: 2.2
  719. .. cfunction:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
  720. Return the next thread state object after *tstate* from the list of all such
  721. objects belonging to the same :ctype:`PyInterpreterState` object.
  722. .. versionadded:: 2.2