1 \chapter{Initialization, Finalization, and Threads
2 \label{initialization
}}
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.
26 \begin{cfuncdesc
}{void
}{Py_InitializeEx
}{int initsigs
}
27 This function works like
\cfunction{Py_Initialize()
} if
28 \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}
33 \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
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
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
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
68 modules may not be freed. Some extensions may not work properly if
69 their initialization routine is called more than once; this can
70 happen if an application calls
\cfunction{Py_Initialize()
} and
71 \cfunction{Py_Finalize()
} more than once.
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
88 \withsubitem{(in module sys)
}{
89 \ttindex{stdout
}\ttindex{stderr
}\ttindex{stdin
}}
91 The return value points to the first thread state created in the new
92 sub-interpreter. This thread state is made in the current thread
93 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
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
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.)
136 \begin{cfuncdesc
}{void
}{Py_EndInterpreter
}{PyThreadState *tstate
}
137 Destroy the (sub-)interpreter represented by the given thread state.
138 The given thread state must be the current thread state. See the
139 discussion of thread states below. When the call returns, the
140 current thread state is
\NULL. All thread states associated with
141 this interpreter are destroyed. (The global interpreter lock must
142 be held before calling this function and is still held when it
143 returns.)
\cfunction{Py_Finalize()
}\ttindex{Py_Finalize()
} will
144 destroy all sub-interpreters that haven't been explicitly destroyed
148 \begin{cfuncdesc
}{void
}{Py_SetProgramName
}{char *name
}
149 This function should be called before
150 \cfunction{Py_Initialize()
}\ttindex{Py_Initialize()
} is called
151 for the first time, if it is called at all. It tells the
152 interpreter the value of the
\code{argv
[0]} argument to the
153 \cfunction{main()
}\ttindex{main()
} function of the program. This is
154 used by
\cfunction{Py_GetPath()
}\ttindex{Py_GetPath()
} and some
155 other functions below to find the Python run-time libraries relative
156 to the interpreter executable. The default value is
157 \code{'python'
}. The argument should point to a zero-terminated
158 character string in static storage whose contents will not change
159 for the duration of the program's execution. No code in the Python
160 interpreter will change the contents of this storage.
163 \begin{cfuncdesc
}{char*
}{Py_GetProgramName
}{}
164 Return the program name set with
165 \cfunction{Py_SetProgramName()
}\ttindex{Py_SetProgramName()
}, or the
166 default. The returned string points into static storage; the caller
167 should not modify its value.
170 \begin{cfuncdesc
}{char*
}{Py_GetPrefix
}{}
171 Return the
\emph{prefix
} for installed platform-independent files.
172 This is derived through a number of complicated rules from the
173 program name set with
\cfunction{Py_SetProgramName()
} and some
174 environment variables; for example, if the program name is
175 \code{'/usr/local/bin/python'
}, the prefix is
\code{'/usr/local'
}.
176 The returned string points into static storage; the caller should
177 not modify its value. This corresponds to the
\makevar{prefix
}
178 variable in the top-level
\file{Makefile
} and the
179 \longprogramopt{prefix
} argument to the
\program{configure
} script
180 at build time. The value is available to Python code as
181 \code{sys.prefix
}. It is only useful on
\UNIX. See also the next
185 \begin{cfuncdesc
}{char*
}{Py_GetExecPrefix
}{}
186 Return the
\emph{exec-prefix
} for installed
187 platform-
\emph{de
}pendent files. This is derived through a number
188 of complicated rules from the program name set with
189 \cfunction{Py_SetProgramName()
} and some environment variables; for
190 example, if the program name is
\code{'/usr/local/bin/python'
}, the
191 exec-prefix is
\code{'/usr/local'
}. The returned string points into
192 static storage; the caller should not modify its value. This
193 corresponds to the
\makevar{exec_prefix
} variable in the top-level
194 \file{Makefile
} and the
\longprogramopt{exec-prefix
} argument to the
195 \program{configure
} script at build time. The value is available
196 to Python code as
\code{sys.exec_prefix
}. It is only useful on
199 Background: The exec-prefix differs from the prefix when platform
200 dependent files (such as executables and shared libraries) are
201 installed in a different directory tree. In a typical installation,
202 platform dependent files may be installed in the
203 \file{/usr/local/plat
} subtree while platform independent may be
204 installed in
\file{/usr/local
}.
206 Generally speaking, a platform is a combination of hardware and
207 software families, e.g. Sparc machines running the Solaris
2.x
208 operating system are considered the same platform, but Intel
209 machines running Solaris
2.x are another platform, and Intel
210 machines running Linux are yet another platform. Different major
211 revisions of the same operating system generally also form different
212 platforms. Non-
\UNIX{} operating systems are a different story; the
213 installation strategies on those systems are so different that the
214 prefix and exec-prefix are meaningless, and set to the empty string.
215 Note that compiled Python bytecode files are platform independent
216 (but not independent from the Python version by which they were
219 System administrators will know how to configure the
\program{mount
}
220 or
\program{automount
} programs to share
\file{/usr/local
} between
221 platforms while having
\file{/usr/local/plat
} be a different
222 filesystem for each platform.
225 \begin{cfuncdesc
}{char*
}{Py_GetProgramFullPath
}{}
226 Return the full program name of the Python executable; this is
227 computed as a side-effect of deriving the default module search path
228 from the program name (set by
229 \cfunction{Py_SetProgramName()
}\ttindex{Py_SetProgramName()
} above).
230 The returned string points into static storage; the caller should
231 not modify its value. The value is available to Python code as
232 \code{sys.executable
}.
233 \withsubitem{(in module sys)
}{\ttindex{executable
}}
236 \begin{cfuncdesc
}{char*
}{Py_GetPath
}{}
237 \indexiii{module
}{search
}{path
}
238 Return the default module search path; this is computed from the
239 program name (set by
\cfunction{Py_SetProgramName()
} above) and some
240 environment variables. The returned string consists of a series of
241 directory names separated by a platform dependent delimiter
242 character. The delimiter character is
\character{:
} on
\UNIX and Mac OS X,
243 \character{;
} on Windows. The returned string points into
244 static storage; the caller should not modify its value. The value
245 is available to Python code as the list
246 \code{sys.path
}\withsubitem{(in module sys)
}{\ttindex{path
}}, which
247 may be modified to change the future search path for loaded
250 % XXX should give the exact rules
253 \begin{cfuncdesc
}{const char*
}{Py_GetVersion
}{}
254 Return the version of this Python interpreter. This is a string
255 that looks something like
258 "
1.5 (
#67, Dec
31 1997,
22:
34:
28)
[GCC
2.7.2.2]"
261 The first word (up to the first space character) is the current
262 Python version; the first three characters are the major and minor
263 version separated by a period. The returned string points into
264 static storage; the caller should not modify its value. The value
265 is available to Python code as
\code{sys.version
}.
266 \withsubitem{(in module sys)
}{\ttindex{version
}}
269 \begin{cfuncdesc
}{const char*
}{Py_GetPlatform
}{}
270 Return the platform identifier for the current platform. On
\UNIX,
271 this is formed from the ``official'' name of the operating system,
272 converted to lower case, followed by the major revision number;
273 e.g., for Solaris
2.x, which is also known as SunOS
5.x, the value
274 is
\code{'sunos5'
}. On Mac OS X, it is
\code{'darwin'
}. On Windows,
275 it is
\code{'win'
}. The returned string points into static storage;
276 the caller should not modify its value. The value is available to
277 Python code as
\code{sys.platform
}.
278 \withsubitem{(in module sys)
}{\ttindex{platform
}}
281 \begin{cfuncdesc
}{const char*
}{Py_GetCopyright
}{}
282 Return the official copyright string for the current Python version,
285 \code{'Copyright
1991-
1995 Stichting Mathematisch Centrum, Amsterdam'
}
287 The returned string points into static storage; the caller should
288 not modify its value. The value is available to Python code as
289 \code{sys.copyright
}.
290 \withsubitem{(in module sys)
}{\ttindex{copyright
}}
293 \begin{cfuncdesc
}{const char*
}{Py_GetCompiler
}{}
294 Return an indication of the compiler used to build the current
295 Python version, in square brackets, for example:
301 The returned string points into static storage; the caller should
302 not modify its value. The value is available to Python code as part
303 of the variable
\code{sys.version
}.
304 \withsubitem{(in module sys)
}{\ttindex{version
}}
307 \begin{cfuncdesc
}{const char*
}{Py_GetBuildInfo
}{}
308 Return information about the sequence number and build date and time
309 of the current Python interpreter instance, for example
312 "
#67, Aug
1 1997,
22:
34:
28"
315 The returned string points into static storage; the caller should
316 not modify its value. The value is available to Python code as part
317 of the variable
\code{sys.version
}.
318 \withsubitem{(in module sys)
}{\ttindex{version
}}
321 \begin{cfuncdesc
}{int
}{PySys_SetArgv
}{int argc, char **argv
}
322 Set
\code{sys.argv
} based on
\var{argc
} and
\var{argv
}. These
323 parameters are similar to those passed to the program's
324 \cfunction{main()
}\ttindex{main()
} function with the difference that
325 the first entry should refer to the script file to be executed
326 rather than the executable hosting the Python interpreter. If there
327 isn't a script that will be run, the first entry in
\var{argv
} can
328 be an empty string. If this function fails to initialize
329 \code{sys.argv
}, a fatal condition is signalled using
330 \cfunction{Py_FatalError()
}\ttindex{Py_FatalError()
}.
331 \withsubitem{(in module sys)
}{\ttindex{argv
}}
332 % XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
336 % XXX Other PySys thingies (doesn't really belong in this chapter)
338 \section{Thread State and the Global Interpreter Lock
341 \index{global interpreter lock
}
342 \index{interpreter lock
}
343 \index{lock, interpreter
}
345 The Python interpreter is not fully thread safe. In order to support
346 multi-threaded Python programs, there's a global lock that must be
347 held by the current thread before it can safely access Python objects.
348 Without the lock, even the simplest operations could cause problems in
349 a multi-threaded program: for example, when two threads simultaneously
350 increment the reference count of the same object, the reference count
351 could end up being incremented only once instead of twice.
353 Therefore, the rule exists that only the thread that has acquired the
354 global interpreter lock may operate on Python objects or call Python/C
355 API functions. In order to support multi-threaded Python programs,
356 the interpreter regularly releases and reacquires the lock --- by
357 default, every
100 bytecode instructions (this can be changed with
358 \withsubitem{(in module sys)
}{\ttindex{setcheckinterval()
}}
359 \function{sys.setcheckinterval()
}). The lock is also released and
360 reacquired around potentially blocking I/O operations like reading or
361 writing a file, so that other threads can run while the thread that
362 requests the I/O is waiting for the I/O operation to complete.
364 The Python interpreter needs to keep some bookkeeping information
365 separate per thread --- for this it uses a data structure called
366 \ctype{PyThreadState
}\ttindex{PyThreadState
}. There's one global
367 variable, however: the pointer to the current
368 \ctype{PyThreadState
}\ttindex{PyThreadState
} structure. While most
369 thread packages have a way to store ``per-thread global data,''
370 Python's internal platform independent thread abstraction doesn't
371 support this yet. Therefore, the current thread state must be
372 manipulated explicitly.
374 This is easy enough in most cases. Most code manipulating the global
375 interpreter lock has the following simple structure:
378 Save the thread state in a local variable.
379 Release the interpreter lock.
380 ...Do some blocking I/O operation...
381 Reacquire the interpreter lock.
382 Restore the thread state from the local variable.
385 This is so common that a pair of macros exists to simplify it:
388 Py_BEGIN_ALLOW_THREADS
389 ...Do some blocking I/O operation...
394 \csimplemacro{Py_BEGIN_ALLOW_THREADS
}\ttindex{Py_BEGIN_ALLOW_THREADS
}
395 macro opens a new block and declares a hidden local variable; the
396 \csimplemacro{Py_END_ALLOW_THREADS
}\ttindex{Py_END_ALLOW_THREADS
}
397 macro closes the block. Another advantage of using these two macros
398 is that when Python is compiled without thread support, they are
399 defined empty, thus saving the thread state and lock manipulations.
401 When thread support is enabled, the block above expands to the
405 PyThreadState *_save;
407 _save = PyEval_SaveThread();
408 ...Do some blocking I/O operation...
409 PyEval_RestoreThread(_save);
412 Using even lower level primitives, we can get roughly the same effect
416 PyThreadState *_save;
418 _save = PyThreadState_Swap(NULL);
419 PyEval_ReleaseLock();
420 ...Do some blocking I/O operation...
421 PyEval_AcquireLock();
422 PyThreadState_Swap(_save);
425 There are some subtle differences; in particular,
426 \cfunction{PyEval_RestoreThread()
}\ttindex{PyEval_RestoreThread()
} saves
427 and restores the value of the global variable
428 \cdata{errno
}\ttindex{errno
}, since the lock manipulation does not
429 guarantee that
\cdata{errno
} is left alone. Also, when thread support
431 \cfunction{PyEval_SaveThread()
}\ttindex{PyEval_SaveThread()
} and
432 \cfunction{PyEval_RestoreThread()
} don't manipulate the lock; in this
433 case,
\cfunction{PyEval_ReleaseLock()
}\ttindex{PyEval_ReleaseLock()
} and
434 \cfunction{PyEval_AcquireLock()
}\ttindex{PyEval_AcquireLock()
} are not
435 available. This is done so that dynamically loaded extensions
436 compiled with thread support enabled can be loaded by an interpreter
437 that was compiled with disabled thread support.
439 The global interpreter lock is used to protect the pointer to the
440 current thread state. When releasing the lock and saving the thread
441 state, the current thread state pointer must be retrieved before the
442 lock is released (since another thread could immediately acquire the
443 lock and store its own thread state in the global variable).
444 Conversely, when acquiring the lock and restoring the thread state,
445 the lock must be acquired before storing the thread state pointer.
447 Why am I going on with so much detail about this? Because when
448 threads are created from C, they don't have the global interpreter
449 lock, nor is there a thread state data structure for them. Such
450 threads must bootstrap themselves into existence, by first creating a
451 thread state data structure, then acquiring the lock, and finally
452 storing their thread state pointer, before they can start using the
453 Python/C API. When they are done, they should reset the thread state
454 pointer, release the lock, and finally free their thread state data
457 Beginning with version
2.3, threads can now take advantage of the
458 \cfunction{PyGILState_*()
} functions to do all of the above
459 automatically. The typical idiom for calling into Python from a C
463 PyGILState_STATE gstate;
464 gstate = PyGILState_Ensure();
466 /* Perform Python actions here. */
467 result = CallSomeFunction();
468 /* evaluate result */
470 /* Release the thread. No Python API allowed beyond this point. */
471 PyGILState_Release(gstate);
474 Note that the
\cfunction{PyGILState_*()
} functions assume there is only
475 one global interpreter (created automatically by
476 \cfunction{Py_Initialize()
}). Python still supports the creation of
477 additional interpreters (using
\cfunction{Py_NewInterpreter()
}), but
478 mixing multiple interpreters and the
\cfunction{PyGILState_*()
} API is
481 \begin{ctypedesc
}{PyInterpreterState
}
482 This data structure represents the state shared by a number of
483 cooperating threads. Threads belonging to the same interpreter
484 share their module administration and a few other internal items.
485 There are no public members in this structure.
487 Threads belonging to different interpreters initially share nothing,
488 except process state like available memory, open file descriptors
489 and such. The global interpreter lock is also shared by all
490 threads, regardless of to which interpreter they belong.
493 \begin{ctypedesc
}{PyThreadState
}
494 This data structure represents the state of a single thread. The
495 only public data member is
\ctype{PyInterpreterState
496 *
}\member{interp
}, which points to this thread's interpreter state.
499 \begin{cfuncdesc
}{void
}{PyEval_InitThreads
}{}
500 Initialize and acquire the global interpreter lock. It should be
501 called in the main thread before creating a second thread or
502 engaging in any other thread operations such as
503 \cfunction{PyEval_ReleaseLock()
}\ttindex{PyEval_ReleaseLock()
} or
504 \code{PyEval_ReleaseThread(
\var{tstate
})
}\ttindex{PyEval_ReleaseThread()
}.
505 It is not needed before calling
506 \cfunction{PyEval_SaveThread()
}\ttindex{PyEval_SaveThread()
} or
507 \cfunction{PyEval_RestoreThread()
}\ttindex{PyEval_RestoreThread()
}.
509 This is a no-op when called for a second time. It is safe to call
510 this function before calling
511 \cfunction{Py_Initialize()
}\ttindex{Py_Initialize()
}.
513 When only the main thread exists, no lock operations are needed.
514 This is a common situation (most Python programs do not use
515 threads), and the lock operations slow the interpreter down a bit.
516 Therefore, the lock is not created initially. This situation is
517 equivalent to having acquired the lock: when there is only a single
518 thread, all object accesses are safe. Therefore, when this function
519 initializes the lock, it also acquires it. Before the Python
520 \module{thread
}\refbimodindex{thread
} module creates a new thread,
521 knowing that either it has the lock or the lock hasn't been created
522 yet, it calls
\cfunction{PyEval_InitThreads()
}. When this call
523 returns, it is guaranteed that the lock has been created and that the
524 calling thread has acquired it.
526 It is
\strong{not
} safe to call this function when it is unknown
527 which thread (if any) currently has the global interpreter lock.
529 This function is not available when thread support is disabled at
533 \begin{cfuncdesc
}{int
}{PyEval_ThreadsInitialized
}{}
534 Returns a non-zero value if
\cfunction{PyEval_InitThreads()
} has been
535 called. This function can be called without holding the lock, and
536 therefore can be used to avoid calls to the locking API when running
537 single-threaded. This function is not available when thread support
538 is disabled at compile time.
\versionadded{2.4}
541 \begin{cfuncdesc
}{void
}{PyEval_AcquireLock
}{}
542 Acquire the global interpreter lock. The lock must have been
543 created earlier. If this thread already has the lock, a deadlock
544 ensues. This function is not available when thread support is
545 disabled at compile time.
548 \begin{cfuncdesc
}{void
}{PyEval_ReleaseLock
}{}
549 Release the global interpreter lock. The lock must have been
550 created earlier. This function is not available when thread support
551 is disabled at compile time.
554 \begin{cfuncdesc
}{void
}{PyEval_AcquireThread
}{PyThreadState *tstate
}
555 Acquire the global interpreter lock and set the current thread
556 state to
\var{tstate
}, which should not be
\NULL. The lock must
557 have been created earlier. If this thread already has the lock,
558 deadlock ensues. This function is not available when thread support
559 is disabled at compile time.
562 \begin{cfuncdesc
}{void
}{PyEval_ReleaseThread
}{PyThreadState *tstate
}
563 Reset the current thread state to
\NULL{} and release the global
564 interpreter lock. The lock must have been created earlier and must
565 be held by the current thread. The
\var{tstate
} argument, which
566 must not be
\NULL, is only used to check that it represents the
567 current thread state --- if it isn't, a fatal error is reported.
568 This function is not available when thread support is disabled at
572 \begin{cfuncdesc
}{PyThreadState*
}{PyEval_SaveThread
}{}
573 Release the interpreter lock (if it has been created and thread
574 support is enabled) and reset the thread state to
\NULL, returning
575 the previous thread state (which is not
\NULL). If the lock has
576 been created, the current thread must have acquired it. (This
577 function is available even when thread support is disabled at
581 \begin{cfuncdesc
}{void
}{PyEval_RestoreThread
}{PyThreadState *tstate
}
582 Acquire the interpreter lock (if it has been created and thread
583 support is enabled) and set the thread state to
\var{tstate
}, which
584 must not be
\NULL. If the lock has been created, the current thread
585 must not have acquired it, otherwise deadlock ensues. (This
586 function is available even when thread support is disabled at
590 The following macros are normally used without a trailing semicolon;
591 look for example usage in the Python source distribution.
593 \begin{csimplemacrodesc
}{Py_BEGIN_ALLOW_THREADS
}
594 This macro expands to
595 \samp{\
{ PyThreadState *_save; _save = PyEval_SaveThread();
}.
596 Note that it contains an opening brace; it must be matched with a
597 following
\csimplemacro{Py_END_ALLOW_THREADS
} macro. See above for
598 further discussion of this macro. It is a no-op when thread support
599 is disabled at compile time.
600 \end{csimplemacrodesc
}
602 \begin{csimplemacrodesc
}{Py_END_ALLOW_THREADS
}
603 This macro expands to
\samp{PyEval_RestoreThread(_save); \
}}.
604 Note that it contains a closing brace; it must be matched with an
605 earlier
\csimplemacro{Py_BEGIN_ALLOW_THREADS
} macro. See above for
606 further discussion of this macro. It is a no-op when thread support
607 is disabled at compile time.
608 \end{csimplemacrodesc
}
610 \begin{csimplemacrodesc
}{Py_BLOCK_THREADS
}
611 This macro expands to
\samp{PyEval_RestoreThread(_save);
}: it is
612 equivalent to
\csimplemacro{Py_END_ALLOW_THREADS
} without the
613 closing brace. It is a no-op when thread support is disabled at
615 \end{csimplemacrodesc
}
617 \begin{csimplemacrodesc
}{Py_UNBLOCK_THREADS
}
618 This macro expands to
\samp{_save = PyEval_SaveThread();
}: it is
619 equivalent to
\csimplemacro{Py_BEGIN_ALLOW_THREADS
} without the
620 opening brace and variable declaration. It is a no-op when thread
621 support is disabled at compile time.
622 \end{csimplemacrodesc
}
624 All of the following functions are only available when thread support
625 is enabled at compile time, and must be called only when the
626 interpreter lock has been created.
628 \begin{cfuncdesc
}{PyInterpreterState*
}{PyInterpreterState_New
}{}
629 Create a new interpreter state object. The interpreter lock need
630 not be held, but may be held if it is necessary to serialize calls
634 \begin{cfuncdesc
}{void
}{PyInterpreterState_Clear
}{PyInterpreterState *interp
}
635 Reset all information in an interpreter state object. The
636 interpreter lock must be held.
639 \begin{cfuncdesc
}{void
}{PyInterpreterState_Delete
}{PyInterpreterState *interp
}
640 Destroy an interpreter state object. The interpreter lock need not
641 be held. The interpreter state must have been reset with a previous
642 call to
\cfunction{PyInterpreterState_Clear()
}.
645 \begin{cfuncdesc
}{PyThreadState*
}{PyThreadState_New
}{PyInterpreterState *interp
}
646 Create a new thread state object belonging to the given interpreter
647 object. The interpreter lock need not be held, but may be held if
648 it is necessary to serialize calls to this function.
651 \begin{cfuncdesc
}{void
}{PyThreadState_Clear
}{PyThreadState *tstate
}
652 Reset all information in a thread state object. The interpreter lock
656 \begin{cfuncdesc
}{void
}{PyThreadState_Delete
}{PyThreadState *tstate
}
657 Destroy a thread state object. The interpreter lock need not be
658 held. The thread state must have been reset with a previous call to
659 \cfunction{PyThreadState_Clear()
}.
662 \begin{cfuncdesc
}{PyThreadState*
}{PyThreadState_Get
}{}
663 Return the current thread state. The interpreter lock must be
664 held. When the current thread state is
\NULL, this issues a fatal
665 error (so that the caller needn't check for
\NULL).
668 \begin{cfuncdesc
}{PyThreadState*
}{PyThreadState_Swap
}{PyThreadState *tstate
}
669 Swap the current thread state with the thread state given by the
670 argument
\var{tstate
}, which may be
\NULL. The interpreter lock
674 \begin{cfuncdesc
}{PyObject*
}{PyThreadState_GetDict
}{}
675 Return a dictionary in which extensions can store thread-specific
676 state information. Each extension should use a unique key to use to
677 store state in the dictionary. It is okay to call this function
678 when no current thread state is available.
679 If this function returns
\NULL, no exception has been raised and the
680 caller should assume no current thread state is available.
681 \versionchanged[Previously this could only be called when a current
682 thread is active, and
\NULL{} meant that an exception was raised
]{2.3}
685 \begin{cfuncdesc
}{int
}{PyThreadState_SetAsyncExc
}{long id, PyObject *exc
}
686 Asynchronously raise an exception in a thread.
687 The
\var{id
} argument is the thread id of the target thread;
688 \var{exc
} is the exception object to be raised.
689 This function does not steal any references to
\var{exc
}.
690 To prevent naive misuse, you must write your own C extension
691 to call this. Must be called with the GIL held.
692 Returns the number of thread states modified; if it returns a number
693 greater than one, you're in trouble, and you should call it again
694 with
\var{exc
} set to
\constant{NULL
} to revert the effect.
695 This raises no exceptions.
699 \begin{cfuncdesc
}{PyGILState_STATE
}{PyGILState_Ensure
}{}
700 Ensure that the current thread is ready to call the Python
701 C API regardless of the current state of Python, or of its
702 thread lock. This may be called as many times as desired
703 by a thread as long as each call is matched with a call to
704 \cfunction{PyGILState_Release()
}.
705 In general, other thread-related APIs may
706 be used between
\cfunction{PyGILState_Ensure()
} and
\cfunction{PyGILState_Release()
} calls as long as the
707 thread state is restored to its previous state before the Release().
708 For example, normal usage of the
\csimplemacro{Py_BEGIN_ALLOW_THREADS
}
709 and
\csimplemacro{Py_END_ALLOW_THREADS
} macros is acceptable.
711 The return value is an opaque "handle" to the thread state when
712 \cfunction{PyGILState_Acquire()
} was called, and must be passed to
713 \cfunction{PyGILState_Release()
} to ensure Python is left in the same
714 state. Even though recursive calls are allowed, these handles
715 \emph{cannot
} be shared - each unique call to
716 \cfunction{PyGILState_Ensure
} must save the handle for its call to
717 \cfunction{PyGILState_Release
}.
719 When the function returns, the current thread will hold the GIL.
720 Failure is a fatal error.
724 \begin{cfuncdesc
}{void
}{PyGILState_Release
}{PyGILState_STATE
}
725 Release any resources previously acquired. After this call, Python's
726 state will be the same as it was prior to the corresponding
727 \cfunction{PyGILState_Ensure
} call (but generally this state will be
728 unknown to the caller, hence the use of the GILState API.)
730 Every call to
\cfunction{PyGILState_Ensure()
} must be matched by a call to
731 \cfunction{PyGILState_Release()
} on the same thread.
736 \section{Profiling and Tracing
\label{profiling
}}
738 \sectionauthor{Fred L. Drake, Jr.
}{fdrake@acm.org
}
740 The Python interpreter provides some low-level support for attaching
741 profiling and execution tracing facilities. These are used for
742 profiling, debugging, and coverage analysis tools.
744 Starting with Python
2.2, the implementation of this facility was
745 substantially revised, and an interface from C was added. This C
746 interface allows the profiling or tracing code to avoid the overhead
747 of calling through Python-level callable objects, making a direct C
748 function call instead. The essential attributes of the facility have
749 not changed; the interface allows trace functions to be installed
750 per-thread, and the basic events reported to the trace function are
751 the same as had been reported to the Python-level trace functions in
754 \begin{ctypedesc
}[Py_tracefunc
]{int
(*Py_tracefunc)(PyObject *obj,
755 PyFrameObject *frame, int what,
757 The type of the trace function registered using
758 \cfunction{PyEval_SetProfile()} and \cfunction{PyEval_SetTrace()}.
759 The first parameter is the object passed to the registration
760 function as \var{obj}, \var{frame} is the frame object to which the
761 event pertains, \var{what} is one of the constants
762 \constant{PyTrace_CALL}, \constant{PyTrace_EXCEPTION},
763 \constant{PyTrace_LINE}, \constant{PyTrace_RETURN},
764 \constant{PyTrace_C_CALL}, \constant{PyTrace_C_EXCEPTION},
765 or \constant{PyTrace_C_RETURN}, and \var{arg}
766 depends on the value of \var{what}:
768 \begin{tableii}{l|l}{constant}{Value of \var{what}}{Meaning of \var{arg}}
769 \lineii{PyTrace_CALL}{Always \NULL.}
770 \lineii{PyTrace_EXCEPTION}{Exception information as returned by
771 \function{sys.exc_info()}.}
772 \lineii{PyTrace_LINE}{Always \NULL.}
773 \lineii{PyTrace_RETURN}{Value being returned to the caller.}
774 \lineii{PyTrace_C_CALL}{Name of function being called.}
775 \lineii{PyTrace_C_EXCEPTION}{Always \NULL.}
776 \lineii{PyTrace_C_RETURN}{Always \NULL.}
780 \begin{cvardesc}{int}{PyTrace_CALL}
781 The value of the \var{what} parameter to a \ctype{Py_tracefunc}
782 function when a new call to a function or method is being reported,
783 or a new entry into a generator. Note that the creation of the
784 iterator for a generator function is not reported as there is no
785 control transfer to the Python bytecode in the corresponding frame.
788 \begin{cvardesc}{int}{PyTrace_EXCEPTION}
789 The value of the \var{what} parameter to a \ctype{Py_tracefunc}
790 function when an exception has been raised. The callback function
791 is called with this value for \var{what} when after any bytecode is
792 processed after which the exception becomes set within the frame
793 being executed. The effect of this is that as exception propagation
794 causes the Python stack to unwind, the callback is called upon
795 return to each frame as the exception propagates. Only trace
796 functions receives these events; they are not needed by the
800 \begin{cvardesc}{int}{PyTrace_LINE}
801 The value passed as the \var{what} parameter to a trace function
802 (but not a profiling function) when a line-number event is being
806 \begin{cvardesc}{int}{PyTrace_RETURN}
807 The value for the \var{what} parameter to \ctype{Py_tracefunc}
808 functions when a call is returning without propagating an exception.
811 \begin{cvardesc}{int}{PyTrace_C_CALL}
812 The value for the \var{what} parameter to \ctype{Py_tracefunc}
813 functions when a C function is about to be called.
816 \begin{cvardesc}{int}{PyTrace_C_EXCEPTION}
817 The value for the \var{what} parameter to \ctype{Py_tracefunc}
818 functions when a C function has thrown an exception.
821 \begin{cvardesc}{int}{PyTrace_C_RETURN}
822 The value for the \var{what} parameter to \ctype{Py_tracefunc}
823 functions when a C function has returned.
826 \begin{cfuncdesc}{void}{PyEval_SetProfile}{Py_tracefunc func, PyObject *obj}
827 Set the profiler function to \var{func}. The \var{obj} parameter is
828 passed to the function as its first parameter, and may be any Python
829 object, or \NULL. If the profile function needs to maintain state,
830 using a different value for \var{obj} for each thread provides a
831 convenient and thread-safe place to store it. The profile function
832 is called for all monitored events except the line-number events.
835 \begin{cfuncdesc}{void}{PyEval_SetTrace}{Py_tracefunc func, PyObject *obj}
836 Set the tracing function to \var{func}. This is similar to
837 \cfunction{PyEval_SetProfile()}, except the tracing function does
838 receive line-number events.
842 \section{Advanced Debugger Support \label{advanced-debugging}}
843 \sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
845 These functions are only intended to be used by advanced debugging
848 \begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Head}{}
849 Return the interpreter state object at the head of the list of all
854 \begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Next}{PyInterpreterState *interp}
855 Return the next interpreter state object after \var{interp} from the
856 list of all such objects.
860 \begin{cfuncdesc}{PyThreadState *}{PyInterpreterState_ThreadHead}{PyInterpreterState *interp}
861 Return the a pointer to the first \ctype{PyThreadState} object in
862 the list of threads associated with the interpreter \var{interp}.
866 \begin{cfuncdesc}{PyThreadState*}{PyThreadState_Next}{PyThreadState *tstate}
867 Return the next thread state object after \var{tstate} from the list
868 of all such objects belonging to the same \ctype{PyInterpreterState}