blob: 51b925f5bdd8af4bea19b33c47244a1894ed99c5 [file] [log] [blame]
Fred Drake3adf79e2001-10-12 19:01:43 +00001\chapter{Initialization, Finalization, and Threads
2 \label{initialization}}
3
4\begin{cfuncdesc}{void}{Py_Initialize}{}
5 Initialize the Python interpreter. In an application embedding
6 Python, this should be called before using any other Python/C API
7 functions; with the exception of
8 \cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
9 \cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
10 \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
11 and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
12 This initializes the table of loaded modules (\code{sys.modules}),
13 and\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}
14 creates the fundamental modules
15 \module{__builtin__}\refbimodindex{__builtin__},
16 \module{__main__}\refbimodindex{__main__} and
17 \module{sys}\refbimodindex{sys}. It also initializes the module
18 search\indexiii{module}{search}{path} path (\code{sys.path}).
19 It does not set \code{sys.argv}; use
20 \cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
21 is a no-op when called for a second time (without calling
22 \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is
23 no return value; it is a fatal error if the initialization fails.
24\end{cfuncdesc}
25
Martin v. Löwis336e85f2004-08-19 11:31:58 +000026\begin{cfuncdesc}{void}{Py_InitializeEx}{int initsigs}
Tim Peters7f468f22004-10-11 02:40:51 +000027 This function works like \cfunction{Py_Initialize()} if
Martin v. Löwis336e85f2004-08-19 11:31:58 +000028 \var{initsigs} is 1. If \var{initsigs} is 0, it skips
29 initialization registration of signal handlers, which
30 might be useful when Python is embedded. \versionadded{2.4}
31\end{cfuncdesc}
32
Fred Drake3adf79e2001-10-12 19:01:43 +000033\begin{cfuncdesc}{int}{Py_IsInitialized}{}
34 Return true (nonzero) when the Python interpreter has been
35 initialized, false (zero) if not. After \cfunction{Py_Finalize()}
36 is called, this returns false until \cfunction{Py_Initialize()} is
37 called again.
38\end{cfuncdesc}
39
40\begin{cfuncdesc}{void}{Py_Finalize}{}
41 Undo all initializations made by \cfunction{Py_Initialize()} and
42 subsequent use of Python/C API functions, and destroy all
43 sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that
44 were created and not yet destroyed since the last call to
45 \cfunction{Py_Initialize()}. Ideally, this frees all memory
46 allocated by the Python interpreter. This is a no-op when called
47 for a second time (without calling \cfunction{Py_Initialize()} again
48 first). There is no return value; errors during finalization are
49 ignored.
50
51 This function is provided for a number of reasons. An embedding
52 application might want to restart Python without having to restart
53 the application itself. An application that has loaded the Python
54 interpreter from a dynamically loadable library (or DLL) might want
55 to free all memory allocated by Python before unloading the
56 DLL. During a hunt for memory leaks in an application a developer
57 might want to free all memory allocated by Python before exiting
58 from the application.
59
60 \strong{Bugs and caveats:} The destruction of modules and objects in
61 modules is done in random order; this may cause destructors
62 (\method{__del__()} methods) to fail when they depend on other
63 objects (even functions) or modules. Dynamically loaded extension
64 modules loaded by Python are not unloaded. Small amounts of memory
65 allocated by the Python interpreter may not be freed (if you find a
66 leak, please report it). Memory tied up in circular references
67 between objects is not freed. Some memory allocated by extension
Michael W. Hudsonbbe17f52003-02-10 19:12:42 +000068 modules may not be freed. Some extensions may not work properly if
Fred Drake3adf79e2001-10-12 19:01:43 +000069 their initialization routine is called more than once; this can
Michael W. Hudsonbbe17f52003-02-10 19:12:42 +000070 happen if an application calls \cfunction{Py_Initialize()} and
Fred Drake3adf79e2001-10-12 19:01:43 +000071 \cfunction{Py_Finalize()} more than once.
72\end{cfuncdesc}
73
74\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
75 Create a new sub-interpreter. This is an (almost) totally separate
76 environment for the execution of Python code. In particular, the
77 new interpreter has separate, independent versions of all imported
78 modules, including the fundamental modules
79 \module{__builtin__}\refbimodindex{__builtin__},
80 \module{__main__}\refbimodindex{__main__} and
81 \module{sys}\refbimodindex{sys}. The table of loaded modules
82 (\code{sys.modules}) and the module search path (\code{sys.path})
83 are also separate. The new environment has no \code{sys.argv}
84 variable. It has new standard I/O stream file objects
85 \code{sys.stdin}, \code{sys.stdout} and \code{sys.stderr} (however
86 these refer to the same underlying \ctype{FILE} structures in the C
87 library).
88 \withsubitem{(in module sys)}{
89 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
90
91 The return value points to the first thread state created in the new
Brett Cannon65d63422004-03-18 01:38:11 +000092 sub-interpreter. This thread state is made in the current thread
Fred Drake3adf79e2001-10-12 19:01:43 +000093 state. Note that no actual thread is created; see the discussion of
94 thread states below. If creation of the new interpreter is
95 unsuccessful, \NULL{} is returned; no exception is set since the
96 exception state is stored in the current thread state and there may
97 not be a current thread state. (Like all other Python/C API
98 functions, the global interpreter lock must be held before calling
99 this function and is still held when it returns; however, unlike
100 most other Python/C API functions, there needn't be a current thread
101 state on entry.)
102
103 Extension modules are shared between (sub-)interpreters as follows:
104 the first time a particular extension is imported, it is initialized
105 normally, and a (shallow) copy of its module's dictionary is
106 squirreled away. When the same extension is imported by another
107 (sub-)interpreter, a new module is initialized and filled with the
108 contents of this copy; the extension's \code{init} function is not
109 called. Note that this is different from what happens when an
110 extension is imported after the interpreter has been completely
111 re-initialized by calling
112 \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
113 \cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
114 the extension's \code{init\var{module}} function \emph{is} called
115 again.
116
117 \strong{Bugs and caveats:} Because sub-interpreters (and the main
118 interpreter) are part of the same process, the insulation between
119 them isn't perfect --- for example, using low-level file operations
120 like \withsubitem{(in module os)}{\ttindex{close()}}
121 \function{os.close()} they can (accidentally or maliciously) affect
122 each other's open files. Because of the way extensions are shared
123 between (sub-)interpreters, some extensions may not work properly;
124 this is especially likely when the extension makes use of (static)
125 global variables, or when the extension manipulates its module's
126 dictionary after its initialization. It is possible to insert
127 objects created in one sub-interpreter into a namespace of another
128 sub-interpreter; this should be done with great care to avoid
129 sharing user-defined functions, methods, instances or classes
130 between sub-interpreters, since import operations executed by such
131 objects may affect the wrong (sub-)interpreter's dictionary of
132 loaded modules. (XXX This is a hard-to-fix bug that will be
133 addressed in a future release.)
Michael W. Hudsonfb662972005-06-20 16:37:03 +0000134
135 Also note that the use of this functionality is incompatible with
136 extension modules such as PyObjC and ctypes that use the
137 \cfunction{PyGILState_*} APIs (and this is inherent in the way the
138 \cfunction{PyGILState_*} functions work). Simple things may work,
139 but confusing behavior will always be near.
Fred Drake3adf79e2001-10-12 19:01:43 +0000140\end{cfuncdesc}
141
142\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
143 Destroy the (sub-)interpreter represented by the given thread state.
144 The given thread state must be the current thread state. See the
145 discussion of thread states below. When the call returns, the
146 current thread state is \NULL. All thread states associated with
Brett Cannon9b976e62004-03-18 00:49:01 +0000147 this interpreter are destroyed. (The global interpreter lock must
Fred Drake3adf79e2001-10-12 19:01:43 +0000148 be held before calling this function and is still held when it
149 returns.) \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will
150 destroy all sub-interpreters that haven't been explicitly destroyed
151 at that point.
152\end{cfuncdesc}
153
154\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
155 This function should be called before
156 \cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
157 for the first time, if it is called at all. It tells the
158 interpreter the value of the \code{argv[0]} argument to the
159 \cfunction{main()}\ttindex{main()} function of the program. This is
160 used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some
161 other functions below to find the Python run-time libraries relative
162 to the interpreter executable. The default value is
163 \code{'python'}. The argument should point to a zero-terminated
164 character string in static storage whose contents will not change
165 for the duration of the program's execution. No code in the Python
166 interpreter will change the contents of this storage.
167\end{cfuncdesc}
168
169\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
170 Return the program name set with
171 \cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
172 default. The returned string points into static storage; the caller
173 should not modify its value.
174\end{cfuncdesc}
175
176\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
177 Return the \emph{prefix} for installed platform-independent files.
178 This is derived through a number of complicated rules from the
179 program name set with \cfunction{Py_SetProgramName()} and some
180 environment variables; for example, if the program name is
181 \code{'/usr/local/bin/python'}, the prefix is \code{'/usr/local'}.
182 The returned string points into static storage; the caller should
183 not modify its value. This corresponds to the \makevar{prefix}
184 variable in the top-level \file{Makefile} and the
185 \longprogramopt{prefix} argument to the \program{configure} script
186 at build time. The value is available to Python code as
187 \code{sys.prefix}. It is only useful on \UNIX. See also the next
188 function.
189\end{cfuncdesc}
190
191\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
192 Return the \emph{exec-prefix} for installed
193 platform-\emph{de}pendent files. This is derived through a number
194 of complicated rules from the program name set with
195 \cfunction{Py_SetProgramName()} and some environment variables; for
196 example, if the program name is \code{'/usr/local/bin/python'}, the
197 exec-prefix is \code{'/usr/local'}. The returned string points into
198 static storage; the caller should not modify its value. This
199 corresponds to the \makevar{exec_prefix} variable in the top-level
200 \file{Makefile} and the \longprogramopt{exec-prefix} argument to the
201 \program{configure} script at build time. The value is available
202 to Python code as \code{sys.exec_prefix}. It is only useful on
203 \UNIX.
204
205 Background: The exec-prefix differs from the prefix when platform
206 dependent files (such as executables and shared libraries) are
207 installed in a different directory tree. In a typical installation,
208 platform dependent files may be installed in the
209 \file{/usr/local/plat} subtree while platform independent may be
210 installed in \file{/usr/local}.
211
212 Generally speaking, a platform is a combination of hardware and
213 software families, e.g. Sparc machines running the Solaris 2.x
214 operating system are considered the same platform, but Intel
215 machines running Solaris 2.x are another platform, and Intel
216 machines running Linux are yet another platform. Different major
217 revisions of the same operating system generally also form different
218 platforms. Non-\UNIX{} operating systems are a different story; the
219 installation strategies on those systems are so different that the
220 prefix and exec-prefix are meaningless, and set to the empty string.
221 Note that compiled Python bytecode files are platform independent
222 (but not independent from the Python version by which they were
223 compiled!).
224
225 System administrators will know how to configure the \program{mount}
226 or \program{automount} programs to share \file{/usr/local} between
227 platforms while having \file{/usr/local/plat} be a different
228 filesystem for each platform.
229\end{cfuncdesc}
230
231\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
232 Return the full program name of the Python executable; this is
233 computed as a side-effect of deriving the default module search path
234 from the program name (set by
235 \cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
236 The returned string points into static storage; the caller should
237 not modify its value. The value is available to Python code as
238 \code{sys.executable}.
239 \withsubitem{(in module sys)}{\ttindex{executable}}
240\end{cfuncdesc}
241
242\begin{cfuncdesc}{char*}{Py_GetPath}{}
243 \indexiii{module}{search}{path}
244 Return the default module search path; this is computed from the
245 program name (set by \cfunction{Py_SetProgramName()} above) and some
246 environment variables. The returned string consists of a series of
247 directory names separated by a platform dependent delimiter
Brett Cannon7706c2d2005-02-13 22:50:04 +0000248 character. The delimiter character is \character{:} on \UNIX and Mac OS X,
249 \character{;} on Windows. The returned string points into
Fred Drake3adf79e2001-10-12 19:01:43 +0000250 static storage; the caller should not modify its value. The value
251 is available to Python code as the list
252 \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}}, which
253 may be modified to change the future search path for loaded
254 modules.
255
256 % XXX should give the exact rules
257\end{cfuncdesc}
258
259\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
260 Return the version of this Python interpreter. This is a string
261 that looks something like
262
263\begin{verbatim}
264"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
265\end{verbatim}
266
267 The first word (up to the first space character) is the current
268 Python version; the first three characters are the major and minor
269 version separated by a period. The returned string points into
270 static storage; the caller should not modify its value. The value
Michael W. Hudsonbbe17f52003-02-10 19:12:42 +0000271 is available to Python code as \code{sys.version}.
Fred Drake3adf79e2001-10-12 19:01:43 +0000272 \withsubitem{(in module sys)}{\ttindex{version}}
273\end{cfuncdesc}
274
275\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
276 Return the platform identifier for the current platform. On \UNIX,
277 this is formed from the ``official'' name of the operating system,
278 converted to lower case, followed by the major revision number;
279 e.g., for Solaris 2.x, which is also known as SunOS 5.x, the value
Brett Cannon7706c2d2005-02-13 22:50:04 +0000280 is \code{'sunos5'}. On Mac OS X, it is \code{'darwin'}. On Windows,
Fred Drake3adf79e2001-10-12 19:01:43 +0000281 it is \code{'win'}. The returned string points into static storage;
282 the caller should not modify its value. The value is available to
283 Python code as \code{sys.platform}.
284 \withsubitem{(in module sys)}{\ttindex{platform}}
285\end{cfuncdesc}
286
287\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
288 Return the official copyright string for the current Python version,
289 for example
290
291 \code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
292
293 The returned string points into static storage; the caller should
Michael W. Hudsonbbe17f52003-02-10 19:12:42 +0000294 not modify its value. The value is available to Python code as
295 \code{sys.copyright}.
Fred Drake3adf79e2001-10-12 19:01:43 +0000296 \withsubitem{(in module sys)}{\ttindex{copyright}}
297\end{cfuncdesc}
298
299\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
300 Return an indication of the compiler used to build the current
301 Python version, in square brackets, for example:
302
303\begin{verbatim}
304"[GCC 2.7.2.2]"
305\end{verbatim}
306
307 The returned string points into static storage; the caller should
308 not modify its value. The value is available to Python code as part
309 of the variable \code{sys.version}.
310 \withsubitem{(in module sys)}{\ttindex{version}}
311\end{cfuncdesc}
312
313\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
314 Return information about the sequence number and build date and time
315 of the current Python interpreter instance, for example
316
317\begin{verbatim}
318"#67, Aug 1 1997, 22:34:28"
319\end{verbatim}
320
321 The returned string points into static storage; the caller should
322 not modify its value. The value is available to Python code as part
323 of the variable \code{sys.version}.
324 \withsubitem{(in module sys)}{\ttindex{version}}
325\end{cfuncdesc}
326
327\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
328 Set \code{sys.argv} based on \var{argc} and \var{argv}. These
329 parameters are similar to those passed to the program's
330 \cfunction{main()}\ttindex{main()} function with the difference that
331 the first entry should refer to the script file to be executed
332 rather than the executable hosting the Python interpreter. If there
333 isn't a script that will be run, the first entry in \var{argv} can
334 be an empty string. If this function fails to initialize
335 \code{sys.argv}, a fatal condition is signalled using
336 \cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
337 \withsubitem{(in module sys)}{\ttindex{argv}}
338 % XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
339 % check w/ Guido.
340\end{cfuncdesc}
341
342% XXX Other PySys thingies (doesn't really belong in this chapter)
343
344\section{Thread State and the Global Interpreter Lock
345 \label{threads}}
346
347\index{global interpreter lock}
348\index{interpreter lock}
349\index{lock, interpreter}
350
351The Python interpreter is not fully thread safe. In order to support
352multi-threaded Python programs, there's a global lock that must be
353held by the current thread before it can safely access Python objects.
354Without the lock, even the simplest operations could cause problems in
355a multi-threaded program: for example, when two threads simultaneously
356increment the reference count of the same object, the reference count
357could end up being incremented only once instead of twice.
358
359Therefore, the rule exists that only the thread that has acquired the
360global interpreter lock may operate on Python objects or call Python/C
361API functions. In order to support multi-threaded Python programs,
362the interpreter regularly releases and reacquires the lock --- by
Skip Montanaroeec26f92003-07-02 21:38:34 +0000363default, every 100 bytecode instructions (this can be changed with
Fred Drake3adf79e2001-10-12 19:01:43 +0000364\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
365\function{sys.setcheckinterval()}). The lock is also released and
366reacquired around potentially blocking I/O operations like reading or
367writing a file, so that other threads can run while the thread that
368requests the I/O is waiting for the I/O operation to complete.
369
370The Python interpreter needs to keep some bookkeeping information
371separate per thread --- for this it uses a data structure called
Andrew M. Kuchlingd9dfe022004-07-10 13:48:54 +0000372\ctype{PyThreadState}\ttindex{PyThreadState}. There's one global
373variable, however: the pointer to the current
Fred Drake3adf79e2001-10-12 19:01:43 +0000374\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
375thread packages have a way to store ``per-thread global data,''
376Python's internal platform independent thread abstraction doesn't
377support this yet. Therefore, the current thread state must be
378manipulated explicitly.
379
380This is easy enough in most cases. Most code manipulating the global
381interpreter lock has the following simple structure:
382
383\begin{verbatim}
384Save the thread state in a local variable.
385Release the interpreter lock.
386...Do some blocking I/O operation...
387Reacquire the interpreter lock.
388Restore the thread state from the local variable.
389\end{verbatim}
390
391This is so common that a pair of macros exists to simplify it:
392
393\begin{verbatim}
394Py_BEGIN_ALLOW_THREADS
395...Do some blocking I/O operation...
396Py_END_ALLOW_THREADS
397\end{verbatim}
398
Fred Drake375e3022002-04-09 21:09:42 +0000399The
400\csimplemacro{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS}
401macro opens a new block and declares a hidden local variable; the
402\csimplemacro{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS}
403macro closes the block. Another advantage of using these two macros
404is that when Python is compiled without thread support, they are
405defined empty, thus saving the thread state and lock manipulations.
Fred Drake3adf79e2001-10-12 19:01:43 +0000406
407When thread support is enabled, the block above expands to the
408following code:
409
410\begin{verbatim}
411 PyThreadState *_save;
412
413 _save = PyEval_SaveThread();
414 ...Do some blocking I/O operation...
415 PyEval_RestoreThread(_save);
416\end{verbatim}
417
418Using even lower level primitives, we can get roughly the same effect
419as follows:
420
421\begin{verbatim}
422 PyThreadState *_save;
423
424 _save = PyThreadState_Swap(NULL);
425 PyEval_ReleaseLock();
426 ...Do some blocking I/O operation...
427 PyEval_AcquireLock();
428 PyThreadState_Swap(_save);
429\end{verbatim}
430
431There are some subtle differences; in particular,
432\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
433and restores the value of the global variable
434\cdata{errno}\ttindex{errno}, since the lock manipulation does not
435guarantee that \cdata{errno} is left alone. Also, when thread support
436is disabled,
437\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
438\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
439case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
440\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
441available. This is done so that dynamically loaded extensions
442compiled with thread support enabled can be loaded by an interpreter
443that was compiled with disabled thread support.
444
445The global interpreter lock is used to protect the pointer to the
446current thread state. When releasing the lock and saving the thread
447state, the current thread state pointer must be retrieved before the
448lock is released (since another thread could immediately acquire the
449lock and store its own thread state in the global variable).
450Conversely, when acquiring the lock and restoring the thread state,
451the lock must be acquired before storing the thread state pointer.
452
453Why am I going on with so much detail about this? Because when
454threads are created from C, they don't have the global interpreter
455lock, nor is there a thread state data structure for them. Such
456threads must bootstrap themselves into existence, by first creating a
457thread state data structure, then acquiring the lock, and finally
458storing their thread state pointer, before they can start using the
459Python/C API. When they are done, they should reset the thread state
460pointer, release the lock, and finally free their thread state data
461structure.
462
Fred Drake14004242005-01-19 04:18:39 +0000463Beginning with version 2.3, threads can now take advantage of the
464\cfunction{PyGILState_*()} functions to do all of the above
465automatically. The typical idiom for calling into Python from a C
466thread is now:
Guido van Rossum41bcbe32003-03-02 13:17:20 +0000467
468\begin{verbatim}
Andrew M. Kuchlingff8113f2004-07-10 13:42:52 +0000469 PyGILState_STATE gstate;
470 gstate = PyGILState_Ensure();
Guido van Rossum41bcbe32003-03-02 13:17:20 +0000471
472 /* Perform Python actions here. */
473 result = CallSomeFunction();
474 /* evaluate result */
475
476 /* Release the thread. No Python API allowed beyond this point. */
Andrew M. Kuchlingff8113f2004-07-10 13:42:52 +0000477 PyGILState_Release(gstate);
Guido van Rossum41bcbe32003-03-02 13:17:20 +0000478\end{verbatim}
Fred Drake3adf79e2001-10-12 19:01:43 +0000479
Michael W. Hudson7b279072005-06-20 12:12:45 +0000480Note that the \cfunction{PyGILState_*()} functions assume there is
481only one global interpreter (created automatically by
Fred Drake14004242005-01-19 04:18:39 +0000482\cfunction{Py_Initialize()}). Python still supports the creation of
Michael W. Hudson7b279072005-06-20 12:12:45 +0000483additional interpreters (using \cfunction{Py_NewInterpreter()}), but
Fred Drake14004242005-01-19 04:18:39 +0000484mixing multiple interpreters and the \cfunction{PyGILState_*()} API is
485unsupported.
486
Fred Drake3adf79e2001-10-12 19:01:43 +0000487\begin{ctypedesc}{PyInterpreterState}
488 This data structure represents the state shared by a number of
489 cooperating threads. Threads belonging to the same interpreter
490 share their module administration and a few other internal items.
491 There are no public members in this structure.
492
493 Threads belonging to different interpreters initially share nothing,
494 except process state like available memory, open file descriptors
495 and such. The global interpreter lock is also shared by all
496 threads, regardless of to which interpreter they belong.
497\end{ctypedesc}
498
499\begin{ctypedesc}{PyThreadState}
500 This data structure represents the state of a single thread. The
501 only public data member is \ctype{PyInterpreterState
502 *}\member{interp}, which points to this thread's interpreter state.
503\end{ctypedesc}
504
505\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
506 Initialize and acquire the global interpreter lock. It should be
507 called in the main thread before creating a second thread or
508 engaging in any other thread operations such as
509 \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
510 \code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
511 It is not needed before calling
512 \cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
513 \cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
514
515 This is a no-op when called for a second time. It is safe to call
516 this function before calling
517 \cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
518
519 When only the main thread exists, no lock operations are needed.
520 This is a common situation (most Python programs do not use
521 threads), and the lock operations slow the interpreter down a bit.
522 Therefore, the lock is not created initially. This situation is
Tim Peters7f468f22004-10-11 02:40:51 +0000523 equivalent to having acquired the lock: when there is only a single
Fred Drake3adf79e2001-10-12 19:01:43 +0000524 thread, all object accesses are safe. Therefore, when this function
525 initializes the lock, it also acquires it. Before the Python
526 \module{thread}\refbimodindex{thread} module creates a new thread,
527 knowing that either it has the lock or the lock hasn't been created
528 yet, it calls \cfunction{PyEval_InitThreads()}. When this call
Tim Peters7f468f22004-10-11 02:40:51 +0000529 returns, it is guaranteed that the lock has been created and that the
530 calling thread has acquired it.
Fred Drake3adf79e2001-10-12 19:01:43 +0000531
532 It is \strong{not} safe to call this function when it is unknown
533 which thread (if any) currently has the global interpreter lock.
534
535 This function is not available when thread support is disabled at
536 compile time.
537\end{cfuncdesc}
538
Tim Peters7f468f22004-10-11 02:40:51 +0000539\begin{cfuncdesc}{int}{PyEval_ThreadsInitialized}{}
540 Returns a non-zero value if \cfunction{PyEval_InitThreads()} has been
541 called. This function can be called without holding the lock, and
542 therefore can be used to avoid calls to the locking API when running
543 single-threaded. This function is not available when thread support
544 is disabled at compile time. \versionadded{2.4}
545\end{cfuncdesc}
546
Fred Drake3adf79e2001-10-12 19:01:43 +0000547\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
548 Acquire the global interpreter lock. The lock must have been
549 created earlier. If this thread already has the lock, a deadlock
550 ensues. This function is not available when thread support is
551 disabled at compile time.
552\end{cfuncdesc}
553
554\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
555 Release the global interpreter lock. The lock must have been
556 created earlier. This function is not available when thread support
557 is disabled at compile time.
558\end{cfuncdesc}
559
560\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Brett Cannon65d63422004-03-18 01:38:11 +0000561 Acquire the global interpreter lock and set the current thread
Fred Drake3adf79e2001-10-12 19:01:43 +0000562 state to \var{tstate}, which should not be \NULL. The lock must
563 have been created earlier. If this thread already has the lock,
564 deadlock ensues. This function is not available when thread support
565 is disabled at compile time.
566\end{cfuncdesc}
567
568\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
569 Reset the current thread state to \NULL{} and release the global
570 interpreter lock. The lock must have been created earlier and must
571 be held by the current thread. The \var{tstate} argument, which
572 must not be \NULL, is only used to check that it represents the
573 current thread state --- if it isn't, a fatal error is reported.
574 This function is not available when thread support is disabled at
575 compile time.
576\end{cfuncdesc}
577
578\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
579 Release the interpreter lock (if it has been created and thread
580 support is enabled) and reset the thread state to \NULL, returning
581 the previous thread state (which is not \NULL). If the lock has
582 been created, the current thread must have acquired it. (This
583 function is available even when thread support is disabled at
584 compile time.)
585\end{cfuncdesc}
586
587\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
588 Acquire the interpreter lock (if it has been created and thread
589 support is enabled) and set the thread state to \var{tstate}, which
590 must not be \NULL. If the lock has been created, the current thread
591 must not have acquired it, otherwise deadlock ensues. (This
592 function is available even when thread support is disabled at
593 compile time.)
594\end{cfuncdesc}
595
596The following macros are normally used without a trailing semicolon;
597look for example usage in the Python source distribution.
598
599\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
600 This macro expands to
601 \samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
602 Note that it contains an opening brace; it must be matched with a
Fred Drake375e3022002-04-09 21:09:42 +0000603 following \csimplemacro{Py_END_ALLOW_THREADS} macro. See above for
604 further discussion of this macro. It is a no-op when thread support
605 is disabled at compile time.
Fred Drake3adf79e2001-10-12 19:01:43 +0000606\end{csimplemacrodesc}
607
608\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
609 This macro expands to \samp{PyEval_RestoreThread(_save); \}}.
610 Note that it contains a closing brace; it must be matched with an
Fred Drake375e3022002-04-09 21:09:42 +0000611 earlier \csimplemacro{Py_BEGIN_ALLOW_THREADS} macro. See above for
612 further discussion of this macro. It is a no-op when thread support
613 is disabled at compile time.
Fred Drake3adf79e2001-10-12 19:01:43 +0000614\end{csimplemacrodesc}
615
616\begin{csimplemacrodesc}{Py_BLOCK_THREADS}
617 This macro expands to \samp{PyEval_RestoreThread(_save);}: it is
Fred Drake375e3022002-04-09 21:09:42 +0000618 equivalent to \csimplemacro{Py_END_ALLOW_THREADS} without the
619 closing brace. It is a no-op when thread support is disabled at
620 compile time.
Fred Drake3adf79e2001-10-12 19:01:43 +0000621\end{csimplemacrodesc}
622
623\begin{csimplemacrodesc}{Py_UNBLOCK_THREADS}
624 This macro expands to \samp{_save = PyEval_SaveThread();}: it is
Fred Drake375e3022002-04-09 21:09:42 +0000625 equivalent to \csimplemacro{Py_BEGIN_ALLOW_THREADS} without the
626 opening brace and variable declaration. It is a no-op when thread
627 support is disabled at compile time.
Fred Drake3adf79e2001-10-12 19:01:43 +0000628\end{csimplemacrodesc}
629
630All of the following functions are only available when thread support
631is enabled at compile time, and must be called only when the
632interpreter lock has been created.
633
634\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
635 Create a new interpreter state object. The interpreter lock need
636 not be held, but may be held if it is necessary to serialize calls
637 to this function.
638\end{cfuncdesc}
639
640\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
641 Reset all information in an interpreter state object. The
642 interpreter lock must be held.
643\end{cfuncdesc}
644
645\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
646 Destroy an interpreter state object. The interpreter lock need not
647 be held. The interpreter state must have been reset with a previous
648 call to \cfunction{PyInterpreterState_Clear()}.
649\end{cfuncdesc}
650
651\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
652 Create a new thread state object belonging to the given interpreter
653 object. The interpreter lock need not be held, but may be held if
654 it is necessary to serialize calls to this function.
655\end{cfuncdesc}
656
657\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
658 Reset all information in a thread state object. The interpreter lock
659 must be held.
660\end{cfuncdesc}
661
662\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
663 Destroy a thread state object. The interpreter lock need not be
664 held. The thread state must have been reset with a previous call to
665 \cfunction{PyThreadState_Clear()}.
666\end{cfuncdesc}
667
668\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
669 Return the current thread state. The interpreter lock must be
670 held. When the current thread state is \NULL, this issues a fatal
671 error (so that the caller needn't check for \NULL).
672\end{cfuncdesc}
673
674\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
675 Swap the current thread state with the thread state given by the
676 argument \var{tstate}, which may be \NULL. The interpreter lock
677 must be held.
678\end{cfuncdesc}
679
680\begin{cfuncdesc}{PyObject*}{PyThreadState_GetDict}{}
681 Return a dictionary in which extensions can store thread-specific
682 state information. Each extension should use a unique key to use to
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000683 store state in the dictionary. It is okay to call this function
684 when no current thread state is available.
685 If this function returns \NULL, no exception has been raised and the
686 caller should assume no current thread state is available.
687 \versionchanged[Previously this could only be called when a current
Fred Drake4ccf6e72003-09-07 02:32:55 +0000688 thread is active, and \NULL{} meant that an exception was raised]{2.3}
Fred Drake3adf79e2001-10-12 19:01:43 +0000689\end{cfuncdesc}
690
Fred Drake6595e152003-06-29 02:14:31 +0000691\begin{cfuncdesc}{int}{PyThreadState_SetAsyncExc}{long id, PyObject *exc}
692 Asynchronously raise an exception in a thread.
693 The \var{id} argument is the thread id of the target thread;
694 \var{exc} is the exception object to be raised.
695 This function does not steal any references to \var{exc}.
696 To prevent naive misuse, you must write your own C extension
697 to call this. Must be called with the GIL held.
698 Returns the number of thread states modified; if it returns a number
699 greater than one, you're in trouble, and you should call it again
700 with \var{exc} set to \constant{NULL} to revert the effect.
701 This raises no exceptions.
702 \versionadded{2.3}
703\end{cfuncdesc}
704
Andrew M. Kuchling371d98a2004-07-10 13:31:18 +0000705\begin{cfuncdesc}{PyGILState_STATE}{PyGILState_Ensure}{}
Michael W. Hudson7b279072005-06-20 12:12:45 +0000706Ensure that the current thread is ready to call the Python C API
707regardless of the current state of Python, or of its thread lock.
708This may be called as many times as desired by a thread as long as
709each call is matched with a call to \cfunction{PyGILState_Release()}.
710In general, other thread-related APIs may be used between
711\cfunction{PyGILState_Ensure()} and \cfunction{PyGILState_Release()}
712calls as long as the thread state is restored to its previous state
713before the Release(). For example, normal usage of the
714\csimplemacro{Py_BEGIN_ALLOW_THREADS} and
715\csimplemacro{Py_END_ALLOW_THREADS} macros is acceptable.
Andrew M. Kuchling371d98a2004-07-10 13:31:18 +0000716
717The return value is an opaque "handle" to the thread state when
718\cfunction{PyGILState_Acquire()} was called, and must be passed to
719\cfunction{PyGILState_Release()} to ensure Python is left in the same
720state. Even though recursive calls are allowed, these handles
721\emph{cannot} be shared - each unique call to
722\cfunction{PyGILState_Ensure} must save the handle for its call to
723\cfunction{PyGILState_Release}.
724
725When the function returns, the current thread will hold the GIL.
726Failure is a fatal error.
727 \versionadded{2.3}
728\end{cfuncdesc}
729
730\begin{cfuncdesc}{void}{PyGILState_Release}{PyGILState_STATE}
731Release any resources previously acquired. After this call, Python's
732state will be the same as it was prior to the corresponding
Andrew M. Kuchlingff8113f2004-07-10 13:42:52 +0000733\cfunction{PyGILState_Ensure} call (but generally this state will be
734unknown to the caller, hence the use of the GILState API.)
Andrew M. Kuchling371d98a2004-07-10 13:31:18 +0000735
736Every call to \cfunction{PyGILState_Ensure()} must be matched by a call to
737\cfunction{PyGILState_Release()} on the same thread.
738 \versionadded{2.3}
739\end{cfuncdesc}
740
Fred Drake3adf79e2001-10-12 19:01:43 +0000741
742\section{Profiling and Tracing \label{profiling}}
743
744\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
745
746The Python interpreter provides some low-level support for attaching
747profiling and execution tracing facilities. These are used for
748profiling, debugging, and coverage analysis tools.
749
750Starting with Python 2.2, the implementation of this facility was
751substantially revised, and an interface from C was added. This C
752interface allows the profiling or tracing code to avoid the overhead
753of calling through Python-level callable objects, making a direct C
754function call instead. The essential attributes of the facility have
755not changed; the interface allows trace functions to be installed
756per-thread, and the basic events reported to the trace function are
757the same as had been reported to the Python-level trace functions in
758previous versions.
759
760\begin{ctypedesc}[Py_tracefunc]{int (*Py_tracefunc)(PyObject *obj,
761 PyFrameObject *frame, int what,
762 PyObject *arg)}
763 The type of the trace function registered using
764 \cfunction{PyEval_SetProfile()} and \cfunction{PyEval_SetTrace()}.
765 The first parameter is the object passed to the registration
766 function as \var{obj}, \var{frame} is the frame object to which the
767 event pertains, \var{what} is one of the constants
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000768 \constant{PyTrace_CALL}, \constant{PyTrace_EXCEPTION},
769 \constant{PyTrace_LINE}, \constant{PyTrace_RETURN},
770 \constant{PyTrace_C_CALL}, \constant{PyTrace_C_EXCEPTION},
771 or \constant{PyTrace_C_RETURN}, and \var{arg}
Fred Drake3adf79e2001-10-12 19:01:43 +0000772 depends on the value of \var{what}:
773
774 \begin{tableii}{l|l}{constant}{Value of \var{what}}{Meaning of \var{arg}}
775 \lineii{PyTrace_CALL}{Always \NULL.}
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000776 \lineii{PyTrace_EXCEPTION}{Exception information as returned by
Fred Drake3adf79e2001-10-12 19:01:43 +0000777 \function{sys.exc_info()}.}
778 \lineii{PyTrace_LINE}{Always \NULL.}
779 \lineii{PyTrace_RETURN}{Value being returned to the caller.}
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000780 \lineii{PyTrace_C_CALL}{Name of function being called.}
781 \lineii{PyTrace_C_EXCEPTION}{Always \NULL.}
782 \lineii{PyTrace_C_RETURN}{Always \NULL.}
Fred Drake3adf79e2001-10-12 19:01:43 +0000783 \end{tableii}
784\end{ctypedesc}
785
786\begin{cvardesc}{int}{PyTrace_CALL}
787 The value of the \var{what} parameter to a \ctype{Py_tracefunc}
788 function when a new call to a function or method is being reported,
789 or a new entry into a generator. Note that the creation of the
790 iterator for a generator function is not reported as there is no
791 control transfer to the Python bytecode in the corresponding frame.
792\end{cvardesc}
793
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000794\begin{cvardesc}{int}{PyTrace_EXCEPTION}
Fred Drake3adf79e2001-10-12 19:01:43 +0000795 The value of the \var{what} parameter to a \ctype{Py_tracefunc}
Fred Drake5bf1ecd2001-10-16 19:23:55 +0000796 function when an exception has been raised. The callback function
797 is called with this value for \var{what} when after any bytecode is
798 processed after which the exception becomes set within the frame
Martin v. Löwis95cf84a2003-10-19 07:32:24 +0000799 being executed. The effect of this is that as exception propagation
Fred Drake5bf1ecd2001-10-16 19:23:55 +0000800 causes the Python stack to unwind, the callback is called upon
Thomas Helleread60e52002-12-06 22:42:13 +0000801 return to each frame as the exception propagates. Only trace
Fred Drake5bf1ecd2001-10-16 19:23:55 +0000802 functions receives these events; they are not needed by the
803 profiler.
Fred Drake3adf79e2001-10-12 19:01:43 +0000804\end{cvardesc}
805
806\begin{cvardesc}{int}{PyTrace_LINE}
807 The value passed as the \var{what} parameter to a trace function
808 (but not a profiling function) when a line-number event is being
809 reported.
810\end{cvardesc}
811
812\begin{cvardesc}{int}{PyTrace_RETURN}
813 The value for the \var{what} parameter to \ctype{Py_tracefunc}
Martin v. Löwis95cf84a2003-10-19 07:32:24 +0000814 functions when a call is returning without propagating an exception.
Fred Drake3adf79e2001-10-12 19:01:43 +0000815\end{cvardesc}
816
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000817\begin{cvardesc}{int}{PyTrace_C_CALL}
818 The value for the \var{what} parameter to \ctype{Py_tracefunc}
819 functions when a C function is about to be called.
820\end{cvardesc}
821
822\begin{cvardesc}{int}{PyTrace_C_EXCEPTION}
823 The value for the \var{what} parameter to \ctype{Py_tracefunc}
824 functions when a C function has thrown an exception.
825\end{cvardesc}
826
827\begin{cvardesc}{int}{PyTrace_C_RETURN}
828 The value for the \var{what} parameter to \ctype{Py_tracefunc}
829 functions when a C function has returned.
830\end{cvardesc}
831
Fred Drake3adf79e2001-10-12 19:01:43 +0000832\begin{cfuncdesc}{void}{PyEval_SetProfile}{Py_tracefunc func, PyObject *obj}
833 Set the profiler function to \var{func}. The \var{obj} parameter is
834 passed to the function as its first parameter, and may be any Python
835 object, or \NULL. If the profile function needs to maintain state,
836 using a different value for \var{obj} for each thread provides a
837 convenient and thread-safe place to store it. The profile function
838 is called for all monitored events except the line-number events.
839\end{cfuncdesc}
840
841\begin{cfuncdesc}{void}{PyEval_SetTrace}{Py_tracefunc func, PyObject *obj}
Raymond Hettingerf17d65d2003-08-12 00:01:16 +0000842 Set the tracing function to \var{func}. This is similar to
Fred Drake3adf79e2001-10-12 19:01:43 +0000843 \cfunction{PyEval_SetProfile()}, except the tracing function does
844 receive line-number events.
845\end{cfuncdesc}
846
847
848\section{Advanced Debugger Support \label{advanced-debugging}}
849\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
850
851These functions are only intended to be used by advanced debugging
852tools.
853
854\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Head}{}
855 Return the interpreter state object at the head of the list of all
856 such objects.
857 \versionadded{2.2}
858\end{cfuncdesc}
859
860\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Next}{PyInterpreterState *interp}
861 Return the next interpreter state object after \var{interp} from the
862 list of all such objects.
863 \versionadded{2.2}
864\end{cfuncdesc}
865
866\begin{cfuncdesc}{PyThreadState *}{PyInterpreterState_ThreadHead}{PyInterpreterState *interp}
867 Return the a pointer to the first \ctype{PyThreadState} object in
868 the list of threads associated with the interpreter \var{interp}.
869 \versionadded{2.2}
870\end{cfuncdesc}
871
872\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Next}{PyThreadState *tstate}
873 Return the next thread state object after \var{tstate} from the list
874 of all such objects belonging to the same \ctype{PyInterpreterState}
875 object.
876 \versionadded{2.2}
877\end{cfuncdesc}