blob: b2fa3ee6e10bd0d0df0c969c4436d163a87b322b [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _initialization:
5
6*****************************************
7Initialization, Finalization, and Threads
8*****************************************
9
10
Antoine Pitrou3acd3e92011-01-15 14:19:53 +000011Initializing and finalizing the interpreter
12===========================================
13
14
Georg Brandl116aa622007-08-15 14:28:22 +000015.. cfunction:: void Py_Initialize()
16
17 .. index::
18 single: Py_SetProgramName()
19 single: PyEval_InitThreads()
20 single: PyEval_ReleaseLock()
21 single: PyEval_AcquireLock()
22 single: modules (in module sys)
23 single: path (in module sys)
Georg Brandl1a3284e2007-12-02 09:40:06 +000024 module: builtins
Georg Brandl116aa622007-08-15 14:28:22 +000025 module: __main__
26 module: sys
27 triple: module; search; path
28 single: PySys_SetArgv()
Antoine Pitrou71d305c2010-05-21 17:33:14 +000029 single: PySys_SetArgvEx()
Georg Brandl116aa622007-08-15 14:28:22 +000030 single: Py_Finalize()
31
32 Initialize the Python interpreter. In an application embedding Python, this
33 should be called before using any other Python/C API functions; with the
34 exception of :cfunc:`Py_SetProgramName`, :cfunc:`PyEval_InitThreads`,
35 :cfunc:`PyEval_ReleaseLock`, and :cfunc:`PyEval_AcquireLock`. This initializes
36 the table of loaded modules (``sys.modules``), and creates the fundamental
Georg Brandl1a3284e2007-12-02 09:40:06 +000037 modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes
Georg Brandl116aa622007-08-15 14:28:22 +000038 the module search path (``sys.path``). It does not set ``sys.argv``; use
Antoine Pitrou71d305c2010-05-21 17:33:14 +000039 :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time
Georg Brandl116aa622007-08-15 14:28:22 +000040 (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a
41 fatal error if the initialization fails.
42
43
44.. cfunction:: void Py_InitializeEx(int initsigs)
45
46 This function works like :cfunc:`Py_Initialize` if *initsigs* is 1. If
47 *initsigs* is 0, it skips initialization registration of signal handlers, which
48 might be useful when Python is embedded.
49
Georg Brandl116aa622007-08-15 14:28:22 +000050
51.. cfunction:: int Py_IsInitialized()
52
53 Return true (nonzero) when the Python interpreter has been initialized, false
54 (zero) if not. After :cfunc:`Py_Finalize` is called, this returns false until
55 :cfunc:`Py_Initialize` is called again.
56
57
58.. cfunction:: void Py_Finalize()
59
60 Undo all initializations made by :cfunc:`Py_Initialize` and subsequent use of
61 Python/C API functions, and destroy all sub-interpreters (see
62 :cfunc:`Py_NewInterpreter` below) that were created and not yet destroyed since
63 the last call to :cfunc:`Py_Initialize`. Ideally, this frees all memory
64 allocated by the Python interpreter. This is a no-op when called for a second
65 time (without calling :cfunc:`Py_Initialize` again first). There is no return
66 value; errors during finalization are ignored.
67
68 This function is provided for a number of reasons. An embedding application
69 might want to restart Python without having to restart the application itself.
70 An application that has loaded the Python interpreter from a dynamically
71 loadable library (or DLL) might want to free all memory allocated by Python
72 before unloading the DLL. During a hunt for memory leaks in an application a
73 developer might want to free all memory allocated by Python before exiting from
74 the application.
75
76 **Bugs and caveats:** The destruction of modules and objects in modules is done
77 in random order; this may cause destructors (:meth:`__del__` methods) to fail
78 when they depend on other objects (even functions) or modules. Dynamically
79 loaded extension modules loaded by Python are not unloaded. Small amounts of
80 memory allocated by the Python interpreter may not be freed (if you find a leak,
81 please report it). Memory tied up in circular references between objects is not
82 freed. Some memory allocated by extension modules may not be freed. Some
83 extensions may not work properly if their initialization routine is called more
84 than once; this can happen if an application calls :cfunc:`Py_Initialize` and
85 :cfunc:`Py_Finalize` more than once.
86
87
Antoine Pitrou3acd3e92011-01-15 14:19:53 +000088Process-wide parameters
89=======================
Georg Brandl116aa622007-08-15 14:28:22 +000090
91
Martin v. Löwis790465f2008-04-05 20:41:37 +000092.. cfunction:: void Py_SetProgramName(wchar_t *name)
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 .. index::
95 single: Py_Initialize()
96 single: main()
97 single: Py_GetPath()
98
99 This function should be called before :cfunc:`Py_Initialize` is called for
100 the first time, if it is called at all. It tells the interpreter the value
Martin v. Löwis790465f2008-04-05 20:41:37 +0000101 of the ``argv[0]`` argument to the :cfunc:`main` function of the program
102 (converted to wide characters).
Georg Brandl116aa622007-08-15 14:28:22 +0000103 This is used by :cfunc:`Py_GetPath` and some other functions below to find
104 the Python run-time libraries relative to the interpreter executable. The
105 default value is ``'python'``. The argument should point to a
Martin v. Löwis790465f2008-04-05 20:41:37 +0000106 zero-terminated wide character string in static storage whose contents will not
Georg Brandl116aa622007-08-15 14:28:22 +0000107 change for the duration of the program's execution. No code in the Python
108 interpreter will change the contents of this storage.
109
110
Benjamin Peterson53991142008-08-17 18:57:58 +0000111.. cfunction:: wchar* Py_GetProgramName()
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113 .. index:: single: Py_SetProgramName()
114
115 Return the program name set with :cfunc:`Py_SetProgramName`, or the default.
116 The returned string points into static storage; the caller should not modify its
117 value.
118
119
Martin v. Löwis790465f2008-04-05 20:41:37 +0000120.. cfunction:: wchar_t* Py_GetPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122 Return the *prefix* for installed platform-independent files. This is derived
123 through a number of complicated rules from the program name set with
124 :cfunc:`Py_SetProgramName` and some environment variables; for example, if the
125 program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
126 returned string points into static storage; the caller should not modify its
127 value. This corresponds to the :makevar:`prefix` variable in the top-level
128 :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure`
129 script at build time. The value is available to Python code as ``sys.prefix``.
130 It is only useful on Unix. See also the next function.
131
132
Martin v. Löwis790465f2008-04-05 20:41:37 +0000133.. cfunction:: wchar_t* Py_GetExecPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135 Return the *exec-prefix* for installed platform-*dependent* files. This is
136 derived through a number of complicated rules from the program name set with
137 :cfunc:`Py_SetProgramName` and some environment variables; for example, if the
138 program name is ``'/usr/local/bin/python'``, the exec-prefix is
139 ``'/usr/local'``. The returned string points into static storage; the caller
140 should not modify its value. This corresponds to the :makevar:`exec_prefix`
141 variable in the top-level :file:`Makefile` and the :option:`--exec-prefix`
142 argument to the :program:`configure` script at build time. The value is
143 available to Python code as ``sys.exec_prefix``. It is only useful on Unix.
144
145 Background: The exec-prefix differs from the prefix when platform dependent
146 files (such as executables and shared libraries) are installed in a different
147 directory tree. In a typical installation, platform dependent files may be
148 installed in the :file:`/usr/local/plat` subtree while platform independent may
149 be installed in :file:`/usr/local`.
150
151 Generally speaking, a platform is a combination of hardware and software
152 families, e.g. Sparc machines running the Solaris 2.x operating system are
153 considered the same platform, but Intel machines running Solaris 2.x are another
154 platform, and Intel machines running Linux are yet another platform. Different
155 major revisions of the same operating system generally also form different
156 platforms. Non-Unix operating systems are a different story; the installation
157 strategies on those systems are so different that the prefix and exec-prefix are
158 meaningless, and set to the empty string. Note that compiled Python bytecode
159 files are platform independent (but not independent from the Python version by
160 which they were compiled!).
161
162 System administrators will know how to configure the :program:`mount` or
163 :program:`automount` programs to share :file:`/usr/local` between platforms
164 while having :file:`/usr/local/plat` be a different filesystem for each
165 platform.
166
167
Martin v. Löwis790465f2008-04-05 20:41:37 +0000168.. cfunction:: wchar_t* Py_GetProgramFullPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170 .. index::
171 single: Py_SetProgramName()
172 single: executable (in module sys)
173
174 Return the full program name of the Python executable; this is computed as a
175 side-effect of deriving the default module search path from the program name
176 (set by :cfunc:`Py_SetProgramName` above). The returned string points into
177 static storage; the caller should not modify its value. The value is available
178 to Python code as ``sys.executable``.
179
180
Martin v. Löwis790465f2008-04-05 20:41:37 +0000181.. cfunction:: wchar_t* Py_GetPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183 .. index::
184 triple: module; search; path
185 single: path (in module sys)
186
Benjamin Petersonffeda292010-01-09 18:48:46 +0000187 Return the default module search path; this is computed from the program name
188 (set by :cfunc:`Py_SetProgramName` above) and some environment variables.
189 The returned string consists of a series of directory names separated by a
190 platform dependent delimiter character. The delimiter character is ``':'``
191 on Unix and Mac OS X, ``';'`` on Windows. The returned string points into
192 static storage; the caller should not modify its value. The list
193 :data:`sys.path` is initialized with this value on interpreter startup; it
194 can be (and usually is) modified later to change the search path for loading
195 modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000197 .. XXX should give the exact rules
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199
200.. cfunction:: const char* Py_GetVersion()
201
202 Return the version of this Python interpreter. This is a string that looks
203 something like ::
204
Georg Brandle6bcc912008-05-12 18:05:20 +0000205 "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207 .. index:: single: version (in module sys)
208
209 The first word (up to the first space character) is the current Python version;
210 the first three characters are the major and minor version separated by a
211 period. The returned string points into static storage; the caller should not
Georg Brandle6bcc912008-05-12 18:05:20 +0000212 modify its value. The value is available to Python code as :data:`sys.version`.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
Georg Brandl116aa622007-08-15 14:28:22 +0000215.. cfunction:: const char* Py_GetPlatform()
216
217 .. index:: single: platform (in module sys)
218
219 Return the platform identifier for the current platform. On Unix, this is
220 formed from the "official" name of the operating system, converted to lower
221 case, followed by the major revision number; e.g., for Solaris 2.x, which is
222 also known as SunOS 5.x, the value is ``'sunos5'``. On Mac OS X, it is
223 ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
224 static storage; the caller should not modify its value. The value is available
225 to Python code as ``sys.platform``.
226
227
228.. cfunction:: const char* Py_GetCopyright()
229
230 Return the official copyright string for the current Python version, for example
231
232 ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
233
234 .. index:: single: copyright (in module sys)
235
236 The returned string points into static storage; the caller should not modify its
237 value. The value is available to Python code as ``sys.copyright``.
238
239
240.. cfunction:: const char* Py_GetCompiler()
241
242 Return an indication of the compiler used to build the current Python version,
243 in square brackets, for example::
244
245 "[GCC 2.7.2.2]"
246
247 .. index:: single: version (in module sys)
248
249 The returned string points into static storage; the caller should not modify its
250 value. The value is available to Python code as part of the variable
251 ``sys.version``.
252
253
254.. cfunction:: const char* Py_GetBuildInfo()
255
256 Return information about the sequence number and build date and time of the
257 current Python interpreter instance, for example ::
258
259 "#67, Aug 1 1997, 22:34:28"
260
261 .. index:: single: version (in module sys)
262
263 The returned string points into static storage; the caller should not modify its
264 value. The value is available to Python code as part of the variable
265 ``sys.version``.
266
267
Antoine Pitrou71d305c2010-05-21 17:33:14 +0000268.. cfunction:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270 .. index::
271 single: main()
272 single: Py_FatalError()
273 single: argv (in module sys)
274
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000275 Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
276 similar to those passed to the program's :cfunc:`main` function with the
277 difference that the first entry should refer to the script file to be
278 executed rather than the executable hosting the Python interpreter. If there
279 isn't a script that will be run, the first entry in *argv* can be an empty
280 string. If this function fails to initialize :data:`sys.argv`, a fatal
281 condition is signalled using :cfunc:`Py_FatalError`.
282
Antoine Pitrou71d305c2010-05-21 17:33:14 +0000283 If *updatepath* is zero, this is all the function does. If *updatepath*
284 is non-zero, the function also modifies :data:`sys.path` according to the
285 following algorithm:
286
287 - If the name of an existing script is passed in ``argv[0]``, the absolute
288 path of the directory where the script is located is prepended to
289 :data:`sys.path`.
290 - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point
291 to an existing file name), an empty string is prepended to
292 :data:`sys.path`, which is the same as prepending the current working
293 directory (``"."``).
294
295 .. note::
296 It is recommended that applications embedding the Python interpreter
297 for purposes other than executing a single script pass 0 as *updatepath*,
298 and update :data:`sys.path` themselves if desired.
299 See `CVE-2008-5983 <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.
300
301 On versions before 3.1.3, you can achieve the same effect by manually
302 popping the first :data:`sys.path` element after having called
303 :cfunc:`PySys_SetArgv`, for example using::
304
305 PyRun_SimpleString("import sys; sys.path.pop(0)\n");
306
307 .. versionadded:: 3.1.3
Georg Brandl116aa622007-08-15 14:28:22 +0000308
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000309 .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
310 check w/ Guido.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Antoine Pitrou71d305c2010-05-21 17:33:14 +0000313.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv)
314
Georg Brandlc62efa82010-07-11 10:41:07 +0000315 This function works like :cfunc:`PySys_SetArgvEx` with *updatepath* set to 1.
Antoine Pitrou71d305c2010-05-21 17:33:14 +0000316
317
Benjamin Petersonb8f68ee2009-09-15 03:38:09 +0000318.. cfunction:: void Py_SetPythonHome(wchar_t *home)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000319
320 Set the default "home" directory, that is, the location of the standard
Georg Brandlf6c8fd62011-02-25 09:48:21 +0000321 Python libraries. See :envvar:`PYTHONHOME` for the meaning of the
322 argument string.
323
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000324 The argument should point to a zero-terminated character string in static
325 storage whose contents will not change for the duration of the program's
326 execution. No code in the Python interpreter will change the contents of
327 this storage.
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000328
329
Benjamin Petersonb8f68ee2009-09-15 03:38:09 +0000330.. cfunction:: w_char* Py_GetPythonHome()
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000331
332 Return the default "home", that is, the value set by a previous call to
333 :cfunc:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
334 environment variable if it is set.
335
336
Georg Brandl116aa622007-08-15 14:28:22 +0000337.. _threads:
338
339Thread State and the Global Interpreter Lock
340============================================
341
342.. index::
343 single: global interpreter lock
344 single: interpreter lock
345 single: lock, interpreter
346
Georg Brandld62ecbf2010-11-26 08:52:36 +0000347The Python interpreter is not fully thread-safe. In order to support
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000348multi-threaded Python programs, there's a global lock, called the :term:`global
349interpreter lock` or :term:`GIL`, that must be held by the current thread before
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000350it can safely access Python objects. Without the lock, even the simplest
351operations could cause problems in a multi-threaded program: for example, when
352two threads simultaneously increment the reference count of the same object, the
353reference count could end up being incremented only once instead of twice.
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355.. index:: single: setcheckinterval() (in module sys)
356
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000357Therefore, the rule exists that only the thread that has acquired the
358:term:`GIL` may operate on Python objects or call Python/C API functions.
359In order to emulate concurrency of execution, the interpreter regularly
360tries to switch threads (see :func:`sys.setcheckinterval`). The lock is also
361released around potentially blocking I/O operations like reading or writing
362a file, so that other Python threads can run in the meantime.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
364.. index::
365 single: PyThreadState
366 single: PyThreadState
367
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000368The Python interpreter keeps some thread-specific bookkeeping information
369inside a data structure called :ctype:`PyThreadState`. There's also one
370global variable pointing to the current :ctype:`PyThreadState`: it can
371be retrieved using :cfunc:`PyThreadState_Get`.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000373Releasing the GIL from extension code
374-------------------------------------
375
376Most extension code manipulating the :term:`GIL` has the following simple
377structure::
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379 Save the thread state in a local variable.
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000380 Release the global interpreter lock.
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000381 ... Do some blocking I/O operation ...
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000382 Reacquire the global interpreter lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000383 Restore the thread state from the local variable.
384
385This is so common that a pair of macros exists to simplify it::
386
387 Py_BEGIN_ALLOW_THREADS
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000388 ... Do some blocking I/O operation ...
Georg Brandl116aa622007-08-15 14:28:22 +0000389 Py_END_ALLOW_THREADS
390
391.. index::
392 single: Py_BEGIN_ALLOW_THREADS
393 single: Py_END_ALLOW_THREADS
394
395The :cmacro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
396hidden local variable; the :cmacro:`Py_END_ALLOW_THREADS` macro closes the
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000397block. These two macros are still available when Python is compiled without
398thread support (they simply have an empty expansion).
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400When thread support is enabled, the block above expands to the following code::
401
402 PyThreadState *_save;
403
404 _save = PyEval_SaveThread();
405 ...Do some blocking I/O operation...
406 PyEval_RestoreThread(_save);
407
Georg Brandl116aa622007-08-15 14:28:22 +0000408.. index::
409 single: PyEval_RestoreThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000410 single: PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000411
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000412Here is how these functions work: the global interpreter lock is used to protect the pointer to the
413current thread state. When releasing the lock and saving the thread state,
414the current thread state pointer must be retrieved before the lock is released
415(since another thread could immediately acquire the lock and store its own thread
416state in the global variable). Conversely, when acquiring the lock and restoring
417the thread state, the lock must be acquired before storing the thread state
418pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000420.. note::
421 Calling system I/O functions is the most common use case for releasing
422 the GIL, but it can also be useful before calling long-running computations
423 which don't need access to Python objects, such as compression or
424 cryptographic functions operating over memory buffers. For example, the
425 standard :mod:`zlib` and :mod:`hashlib` modules release the GIL when
426 compressing or hashing data.
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000428Non-Python created threads
429--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000431When threads are created using the dedicated Python APIs (such as the
432:mod:`threading` module), a thread state is automatically associated to them
433and the code showed above is therefore correct. However, when threads are
434created from C (for example by a third-party library with its own thread
435management), they don't hold the GIL, nor is there a thread state structure
436for them.
437
438If you need to call Python code from these threads (often this will be part
439of a callback API provided by the aforementioned third-party library),
440you must first register these threads with the interpreter by
441creating a thread state data structure, then acquiring the GIL, and finally
442storing their thread state pointer, before you can start using the Python/C
443API. When you are done, you should reset the thread state pointer, release
444the GIL, and finally free the thread state data structure.
445
446The :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` functions do
447all of the above automatically. The typical idiom for calling into Python
448from a C thread is::
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450 PyGILState_STATE gstate;
451 gstate = PyGILState_Ensure();
452
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000453 /* Perform Python actions here. */
Georg Brandl116aa622007-08-15 14:28:22 +0000454 result = CallSomeFunction();
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000455 /* evaluate result or handle exception */
Georg Brandl116aa622007-08-15 14:28:22 +0000456
457 /* Release the thread. No Python API allowed beyond this point. */
458 PyGILState_Release(gstate);
459
460Note that the :cfunc:`PyGILState_\*` functions assume there is only one global
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000461interpreter (created automatically by :cfunc:`Py_Initialize`). Python
Georg Brandl116aa622007-08-15 14:28:22 +0000462supports the creation of additional interpreters (using
463:cfunc:`Py_NewInterpreter`), but mixing multiple interpreters and the
464:cfunc:`PyGILState_\*` API is unsupported.
465
Benjamin Peterson51838562009-10-04 20:35:30 +0000466Another important thing to note about threads is their behaviour in the face
467of the C :cfunc:`fork` call. On most systems with :cfunc:`fork`, after a
468process forks only the thread that issued the fork will exist. That also
469means any locks held by other threads will never be released. Python solves
470this for :func:`os.fork` by acquiring the locks it uses internally before
471the fork, and releasing them afterwards. In addition, it resets any
472:ref:`lock-objects` in the child. When extending or embedding Python, there
473is no way to inform Python of additional (non-Python) locks that need to be
474acquired before or reset after a fork. OS facilities such as
Ezio Melottie4027242011-04-20 21:29:31 +0300475:cfunc:`pthread_atfork` would need to be used to accomplish the same thing.
Benjamin Peterson51838562009-10-04 20:35:30 +0000476Additionally, when extending or embedding Python, calling :cfunc:`fork`
477directly rather than through :func:`os.fork` (and returning to or calling
478into Python) may result in a deadlock by one of Python's internal locks
479being held by a thread that is defunct after the fork.
480:cfunc:`PyOS_AfterFork` tries to reset the necessary locks, but is not
481always able to.
Georg Brandl116aa622007-08-15 14:28:22 +0000482
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000483
484High-level API
485--------------
486
487These are the most commonly used types and functions when writing C extension
488code, or when embedding the Python interpreter:
489
Georg Brandl116aa622007-08-15 14:28:22 +0000490.. ctype:: PyInterpreterState
491
492 This data structure represents the state shared by a number of cooperating
493 threads. Threads belonging to the same interpreter share their module
494 administration and a few other internal items. There are no public members in
495 this structure.
496
497 Threads belonging to different interpreters initially share nothing, except
498 process state like available memory, open file descriptors and such. The global
499 interpreter lock is also shared by all threads, regardless of to which
500 interpreter they belong.
501
502
503.. ctype:: PyThreadState
504
505 This data structure represents the state of a single thread. The only public
506 data member is :ctype:`PyInterpreterState \*`:attr:`interp`, which points to
507 this thread's interpreter state.
508
509
510.. cfunction:: void PyEval_InitThreads()
511
512 .. index::
513 single: PyEval_ReleaseLock()
514 single: PyEval_ReleaseThread()
515 single: PyEval_SaveThread()
516 single: PyEval_RestoreThread()
517
518 Initialize and acquire the global interpreter lock. It should be called in the
519 main thread before creating a second thread or engaging in any other thread
520 operations such as :cfunc:`PyEval_ReleaseLock` or
521 ``PyEval_ReleaseThread(tstate)``. It is not needed before calling
522 :cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_RestoreThread`.
523
524 .. index:: single: Py_Initialize()
525
526 This is a no-op when called for a second time. It is safe to call this function
527 before calling :cfunc:`Py_Initialize`.
528
Georg Brandl2067bfd2008-05-25 13:05:15 +0000529 .. index:: module: _thread
Georg Brandl116aa622007-08-15 14:28:22 +0000530
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000531 .. note::
532 When only the main thread exists, no GIL operations are needed. This is a
533 common situation (most Python programs do not use threads), and the lock
534 operations slow the interpreter down a bit. Therefore, the lock is not
535 created initially. This situation is equivalent to having acquired the lock:
536 when there is only a single thread, all object accesses are safe. Therefore,
537 when this function initializes the global interpreter lock, it also acquires
538 it. Before the Python :mod:`_thread` module creates a new thread, knowing
539 that either it has the lock or the lock hasn't been created yet, it calls
540 :cfunc:`PyEval_InitThreads`. When this call returns, it is guaranteed that
541 the lock has been created and that the calling thread has acquired it.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000543 It is **not** safe to call this function when it is unknown which thread (if
544 any) currently has the global interpreter lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000545
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000546 This function is not available when thread support is disabled at compile time.
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548
549.. cfunction:: int PyEval_ThreadsInitialized()
550
551 Returns a non-zero value if :cfunc:`PyEval_InitThreads` has been called. This
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000552 function can be called without holding the GIL, and therefore can be used to
Georg Brandl116aa622007-08-15 14:28:22 +0000553 avoid calls to the locking API when running single-threaded. This function is
554 not available when thread support is disabled at compile time.
555
Georg Brandl116aa622007-08-15 14:28:22 +0000556
Georg Brandl116aa622007-08-15 14:28:22 +0000557.. cfunction:: PyThreadState* PyEval_SaveThread()
558
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000559 Release the global interpreter lock (if it has been created and thread
560 support is enabled) and reset the thread state to *NULL*, returning the
561 previous thread state (which is not *NULL*). If the lock has been created,
562 the current thread must have acquired it. (This function is available even
563 when thread support is disabled at compile time.)
Georg Brandl116aa622007-08-15 14:28:22 +0000564
565
566.. cfunction:: void PyEval_RestoreThread(PyThreadState *tstate)
567
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000568 Acquire the global interpreter lock (if it has been created and thread
569 support is enabled) and set the thread state to *tstate*, which must not be
570 *NULL*. If the lock has been created, the current thread must not have
571 acquired it, otherwise deadlock ensues. (This function is available even
572 when thread support is disabled at compile time.)
Georg Brandl116aa622007-08-15 14:28:22 +0000573
Christian Heimesd8654cf2007-12-02 15:22:16 +0000574
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000575.. cfunction:: PyThreadState* PyThreadState_Get()
576
577 Return the current thread state. The global interpreter lock must be held.
578 When the current thread state is *NULL*, this issues a fatal error (so that
579 the caller needn't check for *NULL*).
580
581
582.. cfunction:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
583
584 Swap the current thread state with the thread state given by the argument
585 *tstate*, which may be *NULL*. The global interpreter lock must be held
586 and is not released.
587
588
Christian Heimesd8654cf2007-12-02 15:22:16 +0000589.. cfunction:: void PyEval_ReInitThreads()
590
591 This function is called from :cfunc:`PyOS_AfterFork` to ensure that newly
592 created child processes don't hold locks referring to threads which
593 are not running in the child process.
594
595
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000596The following functions use thread-local storage, and are not compatible
597with sub-interpreters:
598
599.. cfunction:: PyGILState_STATE PyGILState_Ensure()
600
601 Ensure that the current thread is ready to call the Python C API regardless
602 of the current state of Python, or of the global interpreter lock. This may
603 be called as many times as desired by a thread as long as each call is
604 matched with a call to :cfunc:`PyGILState_Release`. In general, other
605 thread-related APIs may be used between :cfunc:`PyGILState_Ensure` and
606 :cfunc:`PyGILState_Release` calls as long as the thread state is restored to
607 its previous state before the Release(). For example, normal usage of the
608 :cmacro:`Py_BEGIN_ALLOW_THREADS` and :cmacro:`Py_END_ALLOW_THREADS` macros is
609 acceptable.
610
611 The return value is an opaque "handle" to the thread state when
612 :cfunc:`PyGILState_Ensure` was called, and must be passed to
613 :cfunc:`PyGILState_Release` to ensure Python is left in the same state. Even
614 though recursive calls are allowed, these handles *cannot* be shared - each
615 unique call to :cfunc:`PyGILState_Ensure` must save the handle for its call
616 to :cfunc:`PyGILState_Release`.
617
618 When the function returns, the current thread will hold the GIL and be able
619 to call arbitrary Python code. Failure is a fatal error.
620
621
622.. cfunction:: void PyGILState_Release(PyGILState_STATE)
623
624 Release any resources previously acquired. After this call, Python's state will
625 be the same as it was prior to the corresponding :cfunc:`PyGILState_Ensure` call
626 (but generally this state will be unknown to the caller, hence the use of the
627 GILState API).
628
629 Every call to :cfunc:`PyGILState_Ensure` must be matched by a call to
630 :cfunc:`PyGILState_Release` on the same thread.
631
632
Georg Brandl116aa622007-08-15 14:28:22 +0000633The following macros are normally used without a trailing semicolon; look for
634example usage in the Python source distribution.
635
636
637.. cmacro:: Py_BEGIN_ALLOW_THREADS
638
639 This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
640 Note that it contains an opening brace; it must be matched with a following
641 :cmacro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
642 macro. It is a no-op when thread support is disabled at compile time.
643
644
645.. cmacro:: Py_END_ALLOW_THREADS
646
647 This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
648 a closing brace; it must be matched with an earlier
649 :cmacro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
650 this macro. It is a no-op when thread support is disabled at compile time.
651
652
653.. cmacro:: Py_BLOCK_THREADS
654
655 This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
656 :cmacro:`Py_END_ALLOW_THREADS` without the closing brace. It is a no-op when
657 thread support is disabled at compile time.
658
659
660.. cmacro:: Py_UNBLOCK_THREADS
661
662 This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
663 :cmacro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
664 declaration. It is a no-op when thread support is disabled at compile time.
665
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000666
667Low-level API
668-------------
669
Georg Brandl116aa622007-08-15 14:28:22 +0000670All of the following functions are only available when thread support is enabled
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000671at compile time, and must be called only when the global interpreter lock has
672been created.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674
675.. cfunction:: PyInterpreterState* PyInterpreterState_New()
676
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000677 Create a new interpreter state object. The global interpreter lock need not
678 be held, but may be held if it is necessary to serialize calls to this
679 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000680
681
682.. cfunction:: void PyInterpreterState_Clear(PyInterpreterState *interp)
683
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000684 Reset all information in an interpreter state object. The global interpreter
685 lock must be held.
Georg Brandl116aa622007-08-15 14:28:22 +0000686
687
688.. cfunction:: void PyInterpreterState_Delete(PyInterpreterState *interp)
689
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000690 Destroy an interpreter state object. The global interpreter lock need not be
691 held. The interpreter state must have been reset with a previous call to
Georg Brandl116aa622007-08-15 14:28:22 +0000692 :cfunc:`PyInterpreterState_Clear`.
693
694
695.. cfunction:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
696
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000697 Create a new thread state object belonging to the given interpreter object.
698 The global interpreter lock need not be held, but may be held if it is
699 necessary to serialize calls to this function.
Georg Brandl116aa622007-08-15 14:28:22 +0000700
701
702.. cfunction:: void PyThreadState_Clear(PyThreadState *tstate)
703
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000704 Reset all information in a thread state object. The global interpreter lock
705 must be held.
Georg Brandl116aa622007-08-15 14:28:22 +0000706
707
708.. cfunction:: void PyThreadState_Delete(PyThreadState *tstate)
709
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000710 Destroy a thread state object. The global interpreter lock need not be held.
711 The thread state must have been reset with a previous call to
Georg Brandl116aa622007-08-15 14:28:22 +0000712 :cfunc:`PyThreadState_Clear`.
713
714
Georg Brandl116aa622007-08-15 14:28:22 +0000715.. cfunction:: PyObject* PyThreadState_GetDict()
716
717 Return a dictionary in which extensions can store thread-specific state
718 information. Each extension should use a unique key to use to store state in
719 the dictionary. It is okay to call this function when no current thread state
720 is available. If this function returns *NULL*, no exception has been raised and
721 the caller should assume no current thread state is available.
722
Georg Brandl116aa622007-08-15 14:28:22 +0000723
724.. cfunction:: int PyThreadState_SetAsyncExc(long id, PyObject *exc)
725
726 Asynchronously raise an exception in a thread. The *id* argument is the thread
727 id of the target thread; *exc* is the exception object to be raised. This
728 function does not steal any references to *exc*. To prevent naive misuse, you
729 must write your own C extension to call this. Must be called with the GIL held.
730 Returns the number of thread states modified; this is normally one, but will be
731 zero if the thread id isn't found. If *exc* is :const:`NULL`, the pending
732 exception (if any) for the thread is cleared. This raises no exceptions.
733
Georg Brandl116aa622007-08-15 14:28:22 +0000734
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000735.. cfunction:: void PyEval_AcquireThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000737 Acquire the global interpreter lock and set the current thread state to
738 *tstate*, which should not be *NULL*. The lock must have been created earlier.
739 If this thread already has the lock, deadlock ensues.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000741 :cfunc:`PyEval_RestoreThread` is a higher-level function which is always
742 available (even when thread support isn't enabled or when threads have
743 not been initialized).
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Georg Brandl116aa622007-08-15 14:28:22 +0000745
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000746.. cfunction:: void PyEval_ReleaseThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +0000747
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000748 Reset the current thread state to *NULL* and release the global interpreter
749 lock. The lock must have been created earlier and must be held by the current
750 thread. The *tstate* argument, which must not be *NULL*, is only used to check
751 that it represents the current thread state --- if it isn't, a fatal error is
752 reported.
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000754 :cfunc:`PyEval_SaveThread` is a higher-level function which is always
755 available (even when thread support isn't enabled or when threads have
756 not been initialized).
Georg Brandl116aa622007-08-15 14:28:22 +0000757
Georg Brandl116aa622007-08-15 14:28:22 +0000758
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000759.. cfunction:: void PyEval_AcquireLock()
760
761 Acquire the global interpreter lock. The lock must have been created earlier.
762 If this thread already has the lock, a deadlock ensues.
763
764 .. warning::
765 This function does not change the current thread state. Please use
766 :cfunc:`PyEval_RestoreThread` or :cfunc:`PyEval_AcquireThread`
767 instead.
768
769
770.. cfunction:: void PyEval_ReleaseLock()
771
772 Release the global interpreter lock. The lock must have been created earlier.
773
774 .. warning::
775 This function does not change the current thread state. Please use
776 :cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_ReleaseThread`
777 instead.
778
779
780Sub-interpreter support
781=======================
782
783While in most uses, you will only embed a single Python interpreter, there
784are cases where you need to create several independent interpreters in the
785same process and perhaps even in the same thread. Sub-interpreters allow
786you to do that. You can switch between sub-interpreters using the
787:cfunc:`PyThreadState_Swap` function. You can create and destroy them
788using the following functions:
789
790
791.. cfunction:: PyThreadState* Py_NewInterpreter()
792
793 .. index::
794 module: builtins
795 module: __main__
796 module: sys
797 single: stdout (in module sys)
798 single: stderr (in module sys)
799 single: stdin (in module sys)
800
801 Create a new sub-interpreter. This is an (almost) totally separate environment
802 for the execution of Python code. In particular, the new interpreter has
803 separate, independent versions of all imported modules, including the
804 fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The
805 table of loaded modules (``sys.modules``) and the module search path
806 (``sys.path``) are also separate. The new environment has no ``sys.argv``
807 variable. It has new standard I/O stream file objects ``sys.stdin``,
808 ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
809 file descriptors).
810
811 The return value points to the first thread state created in the new
812 sub-interpreter. This thread state is made in the current thread state.
813 Note that no actual thread is created; see the discussion of thread states
814 below. If creation of the new interpreter is unsuccessful, *NULL* is
815 returned; no exception is set since the exception state is stored in the
816 current thread state and there may not be a current thread state. (Like all
817 other Python/C API functions, the global interpreter lock must be held before
818 calling this function and is still held when it returns; however, unlike most
819 other Python/C API functions, there needn't be a current thread state on
820 entry.)
821
822 .. index::
823 single: Py_Finalize()
824 single: Py_Initialize()
825
826 Extension modules are shared between (sub-)interpreters as follows: the first
827 time a particular extension is imported, it is initialized normally, and a
828 (shallow) copy of its module's dictionary is squirreled away. When the same
829 extension is imported by another (sub-)interpreter, a new module is initialized
830 and filled with the contents of this copy; the extension's ``init`` function is
831 not called. Note that this is different from what happens when an extension is
832 imported after the interpreter has been completely re-initialized by calling
833 :cfunc:`Py_Finalize` and :cfunc:`Py_Initialize`; in that case, the extension's
834 ``initmodule`` function *is* called again.
835
836 .. index:: single: close() (in module os)
837
838
839.. cfunction:: void Py_EndInterpreter(PyThreadState *tstate)
840
841 .. index:: single: Py_Finalize()
842
843 Destroy the (sub-)interpreter represented by the given thread state. The given
844 thread state must be the current thread state. See the discussion of thread
845 states below. When the call returns, the current thread state is *NULL*. All
846 thread states associated with this interpreter are destroyed. (The global
847 interpreter lock must be held before calling this function and is still held
848 when it returns.) :cfunc:`Py_Finalize` will destroy all sub-interpreters that
849 haven't been explicitly destroyed at that point.
850
851
852Bugs and caveats
853----------------
854
855Because sub-interpreters (and the main interpreter) are part of the same
856process, the insulation between them isn't perfect --- for example, using
857low-level file operations like :func:`os.close` they can
858(accidentally or maliciously) affect each other's open files. Because of the
859way extensions are shared between (sub-)interpreters, some extensions may not
860work properly; this is especially likely when the extension makes use of
861(static) global variables, or when the extension manipulates its module's
862dictionary after its initialization. It is possible to insert objects created
863in one sub-interpreter into a namespace of another sub-interpreter; this should
864be done with great care to avoid sharing user-defined functions, methods,
865instances or classes between sub-interpreters, since import operations executed
866by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
867modules.
868
869Also note that combining this functionality with :cfunc:`PyGILState_\*` APIs
Ezio Melottid92ab082011-05-05 14:19:48 +0300870is delicate, because these APIs assume a bijection between Python thread states
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000871and OS-level threads, an assumption broken by the presence of sub-interpreters.
872It is highly recommended that you don't switch sub-interpreters between a pair
873of matching :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` calls.
874Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
875of Python code from non-Python created threads will probably be broken when using
876sub-interpreters.
877
Benjamin Petersona54c9092009-01-13 02:11:23 +0000878
879Asynchronous Notifications
880==========================
881
Benjamin Petersond23f8222009-04-05 19:13:16 +0000882A mechanism is provided to make asynchronous notifications to the main
Benjamin Petersona54c9092009-01-13 02:11:23 +0000883interpreter thread. These notifications take the form of a function
884pointer and a void argument.
885
886.. index:: single: setcheckinterval() (in module sys)
887
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000888Every check interval, when the global interpreter lock is released and
Ezio Melotti890c1932009-12-19 23:33:46 +0000889reacquired, Python will also call any such provided functions. This can be used
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000890for example by asynchronous IO handlers. The notification can be scheduled from
891a worker thread and the actual call than made at the earliest convenience by the
892main thread where it has possession of the global interpreter lock and can
893perform any Python API calls.
Benjamin Petersona54c9092009-01-13 02:11:23 +0000894
Ezio Melottif95033b2011-04-28 00:48:46 +0300895.. cfunction:: int Py_AddPendingCall(int (*func)(void *), void *arg)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000896
897 .. index:: single: Py_AddPendingCall()
898
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000899 Post a notification to the Python main thread. If successful, *func* will be
900 called with the argument *arg* at the earliest convenience. *func* will be
901 called having the global interpreter lock held and can thus use the full
902 Python API and can take any action such as setting object attributes to
903 signal IO completion. It must return 0 on success, or -1 signalling an
904 exception. The notification function won't be interrupted to perform another
905 asynchronous notification recursively, but it can still be interrupted to
906 switch threads if the global interpreter lock is released, for example, if it
Ezio Melotti890c1932009-12-19 23:33:46 +0000907 calls back into Python code.
Benjamin Petersona54c9092009-01-13 02:11:23 +0000908
909 This function returns 0 on success in which case the notification has been
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000910 scheduled. Otherwise, for example if the notification buffer is full, it
911 returns -1 without setting any exception.
Benjamin Petersona54c9092009-01-13 02:11:23 +0000912
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000913 This function can be called on any thread, be it a Python thread or some
914 other system thread. If it is a Python thread, it doesn't matter if it holds
915 the global interpreter lock or not.
Benjamin Petersona54c9092009-01-13 02:11:23 +0000916
Georg Brandl705d9d52009-05-05 09:29:50 +0000917 .. versionadded:: 3.1
Benjamin Petersona54c9092009-01-13 02:11:23 +0000918
919
Georg Brandl116aa622007-08-15 14:28:22 +0000920.. _profiling:
921
922Profiling and Tracing
923=====================
924
925.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
926
927
928The Python interpreter provides some low-level support for attaching profiling
929and execution tracing facilities. These are used for profiling, debugging, and
930coverage analysis tools.
931
Georg Brandle6bcc912008-05-12 18:05:20 +0000932This C interface allows the profiling or tracing code to avoid the overhead of
933calling through Python-level callable objects, making a direct C function call
934instead. The essential attributes of the facility have not changed; the
935interface allows trace functions to be installed per-thread, and the basic
936events reported to the trace function are the same as had been reported to the
937Python-level trace functions in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +0000938
939
940.. ctype:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
941
942 The type of the trace function registered using :cfunc:`PyEval_SetProfile` and
943 :cfunc:`PyEval_SetTrace`. The first parameter is the object passed to the
944 registration function as *obj*, *frame* is the frame object to which the event
945 pertains, *what* is one of the constants :const:`PyTrace_CALL`,
946 :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`,
947 :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, or
948 :const:`PyTrace_C_RETURN`, and *arg* depends on the value of *what*:
949
950 +------------------------------+--------------------------------------+
951 | Value of *what* | Meaning of *arg* |
952 +==============================+======================================+
953 | :const:`PyTrace_CALL` | Always *NULL*. |
954 +------------------------------+--------------------------------------+
955 | :const:`PyTrace_EXCEPTION` | Exception information as returned by |
956 | | :func:`sys.exc_info`. |
957 +------------------------------+--------------------------------------+
958 | :const:`PyTrace_LINE` | Always *NULL*. |
959 +------------------------------+--------------------------------------+
Georg Brandlc524cff2010-11-26 08:42:45 +0000960 | :const:`PyTrace_RETURN` | Value being returned to the caller, |
961 | | or *NULL* if caused by an exception. |
Georg Brandl116aa622007-08-15 14:28:22 +0000962 +------------------------------+--------------------------------------+
Georg Brandlc524cff2010-11-26 08:42:45 +0000963 | :const:`PyTrace_C_CALL` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +0000964 +------------------------------+--------------------------------------+
Georg Brandlc524cff2010-11-26 08:42:45 +0000965 | :const:`PyTrace_C_EXCEPTION` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +0000966 +------------------------------+--------------------------------------+
Georg Brandlc524cff2010-11-26 08:42:45 +0000967 | :const:`PyTrace_C_RETURN` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +0000968 +------------------------------+--------------------------------------+
969
970
971.. cvar:: int PyTrace_CALL
972
973 The value of the *what* parameter to a :ctype:`Py_tracefunc` function when a new
974 call to a function or method is being reported, or a new entry into a generator.
975 Note that the creation of the iterator for a generator function is not reported
976 as there is no control transfer to the Python bytecode in the corresponding
977 frame.
978
979
980.. cvar:: int PyTrace_EXCEPTION
981
982 The value of the *what* parameter to a :ctype:`Py_tracefunc` function when an
983 exception has been raised. The callback function is called with this value for
984 *what* when after any bytecode is processed after which the exception becomes
985 set within the frame being executed. The effect of this is that as exception
986 propagation causes the Python stack to unwind, the callback is called upon
987 return to each frame as the exception propagates. Only trace functions receives
988 these events; they are not needed by the profiler.
989
990
991.. cvar:: int PyTrace_LINE
992
993 The value passed as the *what* parameter to a trace function (but not a
994 profiling function) when a line-number event is being reported.
995
996
997.. cvar:: int PyTrace_RETURN
998
999 The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a
1000 call is returning without propagating an exception.
1001
1002
1003.. cvar:: int PyTrace_C_CALL
1004
1005 The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
1006 function is about to be called.
1007
1008
1009.. cvar:: int PyTrace_C_EXCEPTION
1010
1011 The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
Georg Brandl13f959b2010-10-06 08:35:38 +00001012 function has raised an exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001013
1014
1015.. cvar:: int PyTrace_C_RETURN
1016
1017 The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
1018 function has returned.
1019
1020
1021.. cfunction:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
1022
1023 Set the profiler function to *func*. The *obj* parameter is passed to the
1024 function as its first parameter, and may be any Python object, or *NULL*. If
1025 the profile function needs to maintain state, using a different value for *obj*
1026 for each thread provides a convenient and thread-safe place to store it. The
1027 profile function is called for all monitored events except the line-number
1028 events.
1029
1030
1031.. cfunction:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
1032
1033 Set the tracing function to *func*. This is similar to
1034 :cfunc:`PyEval_SetProfile`, except the tracing function does receive line-number
1035 events.
1036
Christian Heimesd8654cf2007-12-02 15:22:16 +00001037.. cfunction:: PyObject* PyEval_GetCallStats(PyObject *self)
1038
1039 Return a tuple of function call counts. There are constants defined for the
1040 positions within the tuple:
Georg Brandl48310cd2009-01-03 21:18:54 +00001041
Christian Heimesd8654cf2007-12-02 15:22:16 +00001042 +-------------------------------+-------+
1043 | Name | Value |
1044 +===============================+=======+
1045 | :const:`PCALL_ALL` | 0 |
1046 +-------------------------------+-------+
1047 | :const:`PCALL_FUNCTION` | 1 |
1048 +-------------------------------+-------+
1049 | :const:`PCALL_FAST_FUNCTION` | 2 |
1050 +-------------------------------+-------+
1051 | :const:`PCALL_FASTER_FUNCTION`| 3 |
1052 +-------------------------------+-------+
1053 | :const:`PCALL_METHOD` | 4 |
1054 +-------------------------------+-------+
1055 | :const:`PCALL_BOUND_METHOD` | 5 |
1056 +-------------------------------+-------+
1057 | :const:`PCALL_CFUNCTION` | 6 |
1058 +-------------------------------+-------+
1059 | :const:`PCALL_TYPE` | 7 |
1060 +-------------------------------+-------+
1061 | :const:`PCALL_GENERATOR` | 8 |
1062 +-------------------------------+-------+
1063 | :const:`PCALL_OTHER` | 9 |
1064 +-------------------------------+-------+
1065 | :const:`PCALL_POP` | 10 |
1066 +-------------------------------+-------+
Georg Brandl48310cd2009-01-03 21:18:54 +00001067
Christian Heimesd8654cf2007-12-02 15:22:16 +00001068 :const:`PCALL_FAST_FUNCTION` means no argument tuple needs to be created.
1069 :const:`PCALL_FASTER_FUNCTION` means that the fast-path frame setup code is used.
1070
1071 If there is a method call where the call can be optimized by changing
1072 the argument tuple and calling the function directly, it gets recorded
1073 twice.
1074
1075 This function is only present if Python is compiled with :const:`CALL_PROFILE`
1076 defined.
Georg Brandl116aa622007-08-15 14:28:22 +00001077
1078.. _advanced-debugging:
1079
1080Advanced Debugger Support
1081=========================
1082
1083.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1084
1085
1086These functions are only intended to be used by advanced debugging tools.
1087
1088
1089.. cfunction:: PyInterpreterState* PyInterpreterState_Head()
1090
1091 Return the interpreter state object at the head of the list of all such objects.
1092
Georg Brandl116aa622007-08-15 14:28:22 +00001093
1094.. cfunction:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
1095
1096 Return the next interpreter state object after *interp* from the list of all
1097 such objects.
1098
Georg Brandl116aa622007-08-15 14:28:22 +00001099
1100.. cfunction:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
1101
1102 Return the a pointer to the first :ctype:`PyThreadState` object in the list of
1103 threads associated with the interpreter *interp*.
1104
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106.. cfunction:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
1107
1108 Return the next thread state object after *tstate* from the list of all such
1109 objects belonging to the same :ctype:`PyInterpreterState` object.
1110