Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | .. highlightlang:: c |
| 2 | |
| 3 | |
| 4 | .. _initialization: |
| 5 | |
| 6 | ***************************************** |
| 7 | Initialization, Finalization, and Threads |
| 8 | ***************************************** |
| 9 | |
| 10 | |
| 11 | .. cfunction:: void Py_Initialize() |
| 12 | |
| 13 | .. index:: |
| 14 | single: Py_SetProgramName() |
| 15 | single: PyEval_InitThreads() |
| 16 | single: PyEval_ReleaseLock() |
| 17 | single: PyEval_AcquireLock() |
| 18 | single: modules (in module sys) |
| 19 | single: path (in module sys) |
| 20 | module: __builtin__ |
| 21 | module: __main__ |
| 22 | module: sys |
| 23 | triple: module; search; path |
| 24 | single: PySys_SetArgv() |
Antoine Pitrou | 6a26560 | 2010-05-21 17:12:38 +0000 | [diff] [blame] | 25 | single: PySys_SetArgvEx() |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 26 | single: Py_Finalize() |
| 27 | |
| 28 | Initialize the Python interpreter. In an application embedding Python, this |
| 29 | should be called before using any other Python/C API functions; with the |
| 30 | exception of :cfunc:`Py_SetProgramName`, :cfunc:`PyEval_InitThreads`, |
| 31 | :cfunc:`PyEval_ReleaseLock`, and :cfunc:`PyEval_AcquireLock`. This initializes |
| 32 | the table of loaded modules (``sys.modules``), and creates the fundamental |
| 33 | modules :mod:`__builtin__`, :mod:`__main__` and :mod:`sys`. It also initializes |
| 34 | the module search path (``sys.path``). It does not set ``sys.argv``; use |
Antoine Pitrou | 6a26560 | 2010-05-21 17:12:38 +0000 | [diff] [blame] | 35 | :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 36 | (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a |
| 37 | fatal error if the initialization fails. |
| 38 | |
| 39 | |
| 40 | .. cfunction:: void Py_InitializeEx(int initsigs) |
| 41 | |
| 42 | This function works like :cfunc:`Py_Initialize` if *initsigs* is 1. If |
| 43 | *initsigs* is 0, it skips initialization registration of signal handlers, which |
| 44 | might be useful when Python is embedded. |
| 45 | |
| 46 | .. versionadded:: 2.4 |
| 47 | |
| 48 | |
| 49 | .. cfunction:: int Py_IsInitialized() |
| 50 | |
| 51 | Return true (nonzero) when the Python interpreter has been initialized, false |
| 52 | (zero) if not. After :cfunc:`Py_Finalize` is called, this returns false until |
| 53 | :cfunc:`Py_Initialize` is called again. |
| 54 | |
| 55 | |
| 56 | .. cfunction:: void Py_Finalize() |
| 57 | |
| 58 | Undo all initializations made by :cfunc:`Py_Initialize` and subsequent use of |
| 59 | Python/C API functions, and destroy all sub-interpreters (see |
| 60 | :cfunc:`Py_NewInterpreter` below) that were created and not yet destroyed since |
| 61 | the last call to :cfunc:`Py_Initialize`. Ideally, this frees all memory |
| 62 | allocated by the Python interpreter. This is a no-op when called for a second |
| 63 | time (without calling :cfunc:`Py_Initialize` again first). There is no return |
| 64 | value; errors during finalization are ignored. |
| 65 | |
| 66 | This function is provided for a number of reasons. An embedding application |
| 67 | might want to restart Python without having to restart the application itself. |
| 68 | An application that has loaded the Python interpreter from a dynamically |
| 69 | loadable library (or DLL) might want to free all memory allocated by Python |
| 70 | before unloading the DLL. During a hunt for memory leaks in an application a |
| 71 | developer might want to free all memory allocated by Python before exiting from |
| 72 | the application. |
| 73 | |
| 74 | **Bugs and caveats:** The destruction of modules and objects in modules is done |
| 75 | in random order; this may cause destructors (:meth:`__del__` methods) to fail |
| 76 | when they depend on other objects (even functions) or modules. Dynamically |
| 77 | loaded extension modules loaded by Python are not unloaded. Small amounts of |
| 78 | memory allocated by the Python interpreter may not be freed (if you find a leak, |
| 79 | please report it). Memory tied up in circular references between objects is not |
| 80 | freed. Some memory allocated by extension modules may not be freed. Some |
| 81 | extensions may not work properly if their initialization routine is called more |
| 82 | than once; this can happen if an application calls :cfunc:`Py_Initialize` and |
| 83 | :cfunc:`Py_Finalize` more than once. |
| 84 | |
| 85 | |
| 86 | .. cfunction:: PyThreadState* Py_NewInterpreter() |
| 87 | |
| 88 | .. index:: |
| 89 | module: __builtin__ |
| 90 | module: __main__ |
| 91 | module: sys |
| 92 | single: stdout (in module sys) |
| 93 | single: stderr (in module sys) |
| 94 | single: stdin (in module sys) |
| 95 | |
| 96 | Create a new sub-interpreter. This is an (almost) totally separate environment |
| 97 | for the execution of Python code. In particular, the new interpreter has |
| 98 | separate, independent versions of all imported modules, including the |
| 99 | fundamental modules :mod:`__builtin__`, :mod:`__main__` and :mod:`sys`. The |
| 100 | table of loaded modules (``sys.modules``) and the module search path |
| 101 | (``sys.path``) are also separate. The new environment has no ``sys.argv`` |
| 102 | variable. It has new standard I/O stream file objects ``sys.stdin``, |
| 103 | ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying |
| 104 | :ctype:`FILE` structures in the C library). |
| 105 | |
| 106 | The return value points to the first thread state created in the new |
| 107 | sub-interpreter. This thread state is made in the current thread state. |
| 108 | Note that no actual thread is created; see the discussion of thread states |
| 109 | below. If creation of the new interpreter is unsuccessful, *NULL* is |
| 110 | returned; no exception is set since the exception state is stored in the |
| 111 | current thread state and there may not be a current thread state. (Like all |
| 112 | other Python/C API functions, the global interpreter lock must be held before |
| 113 | calling this function and is still held when it returns; however, unlike most |
| 114 | other Python/C API functions, there needn't be a current thread state on |
| 115 | entry.) |
| 116 | |
| 117 | .. index:: |
| 118 | single: Py_Finalize() |
| 119 | single: Py_Initialize() |
| 120 | |
| 121 | Extension modules are shared between (sub-)interpreters as follows: the first |
| 122 | time a particular extension is imported, it is initialized normally, and a |
| 123 | (shallow) copy of its module's dictionary is squirreled away. When the same |
| 124 | extension is imported by another (sub-)interpreter, a new module is initialized |
| 125 | and filled with the contents of this copy; the extension's ``init`` function is |
| 126 | not called. Note that this is different from what happens when an extension is |
| 127 | imported after the interpreter has been completely re-initialized by calling |
| 128 | :cfunc:`Py_Finalize` and :cfunc:`Py_Initialize`; in that case, the extension's |
| 129 | ``initmodule`` function *is* called again. |
| 130 | |
| 131 | .. index:: single: close() (in module os) |
| 132 | |
| 133 | **Bugs and caveats:** Because sub-interpreters (and the main interpreter) are |
| 134 | part of the same process, the insulation between them isn't perfect --- for |
| 135 | example, using low-level file operations like :func:`os.close` they can |
| 136 | (accidentally or maliciously) affect each other's open files. Because of the |
| 137 | way extensions are shared between (sub-)interpreters, some extensions may not |
| 138 | work properly; this is especially likely when the extension makes use of |
| 139 | (static) global variables, or when the extension manipulates its module's |
| 140 | dictionary after its initialization. It is possible to insert objects created |
| 141 | in one sub-interpreter into a namespace of another sub-interpreter; this should |
| 142 | be done with great care to avoid sharing user-defined functions, methods, |
| 143 | instances or classes between sub-interpreters, since import operations executed |
| 144 | by such objects may affect the wrong (sub-)interpreter's dictionary of loaded |
| 145 | modules. (XXX This is a hard-to-fix bug that will be addressed in a future |
| 146 | release.) |
| 147 | |
| 148 | Also note that the use of this functionality is incompatible with extension |
| 149 | modules such as PyObjC and ctypes that use the :cfunc:`PyGILState_\*` APIs (and |
| 150 | this is inherent in the way the :cfunc:`PyGILState_\*` functions work). Simple |
| 151 | things may work, but confusing behavior will always be near. |
| 152 | |
| 153 | |
| 154 | .. cfunction:: void Py_EndInterpreter(PyThreadState *tstate) |
| 155 | |
| 156 | .. index:: single: Py_Finalize() |
| 157 | |
| 158 | Destroy the (sub-)interpreter represented by the given thread state. The given |
| 159 | thread state must be the current thread state. See the discussion of thread |
| 160 | states below. When the call returns, the current thread state is *NULL*. All |
| 161 | thread states associated with this interpreter are destroyed. (The global |
| 162 | interpreter lock must be held before calling this function and is still held |
| 163 | when it returns.) :cfunc:`Py_Finalize` will destroy all sub-interpreters that |
| 164 | haven't been explicitly destroyed at that point. |
| 165 | |
| 166 | |
| 167 | .. cfunction:: void Py_SetProgramName(char *name) |
| 168 | |
| 169 | .. index:: |
| 170 | single: Py_Initialize() |
| 171 | single: main() |
| 172 | single: Py_GetPath() |
| 173 | |
| 174 | This function should be called before :cfunc:`Py_Initialize` is called for |
| 175 | the first time, if it is called at all. It tells the interpreter the value |
| 176 | of the ``argv[0]`` argument to the :cfunc:`main` function of the program. |
| 177 | This is used by :cfunc:`Py_GetPath` and some other functions below to find |
| 178 | the Python run-time libraries relative to the interpreter executable. The |
| 179 | default value is ``'python'``. The argument should point to a |
| 180 | zero-terminated character string in static storage whose contents will not |
| 181 | change for the duration of the program's execution. No code in the Python |
| 182 | interpreter will change the contents of this storage. |
| 183 | |
| 184 | |
| 185 | .. cfunction:: char* Py_GetProgramName() |
| 186 | |
| 187 | .. index:: single: Py_SetProgramName() |
| 188 | |
| 189 | Return the program name set with :cfunc:`Py_SetProgramName`, or the default. |
| 190 | The returned string points into static storage; the caller should not modify its |
| 191 | value. |
| 192 | |
| 193 | |
| 194 | .. cfunction:: char* Py_GetPrefix() |
| 195 | |
| 196 | Return the *prefix* for installed platform-independent files. This is derived |
| 197 | through a number of complicated rules from the program name set with |
| 198 | :cfunc:`Py_SetProgramName` and some environment variables; for example, if the |
| 199 | program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The |
| 200 | returned string points into static storage; the caller should not modify its |
| 201 | value. This corresponds to the :makevar:`prefix` variable in the top-level |
| 202 | :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure` |
| 203 | script at build time. The value is available to Python code as ``sys.prefix``. |
| 204 | It is only useful on Unix. See also the next function. |
| 205 | |
| 206 | |
| 207 | .. cfunction:: char* Py_GetExecPrefix() |
| 208 | |
| 209 | Return the *exec-prefix* for installed platform-*dependent* files. This is |
| 210 | derived through a number of complicated rules from the program name set with |
| 211 | :cfunc:`Py_SetProgramName` and some environment variables; for example, if the |
| 212 | program name is ``'/usr/local/bin/python'``, the exec-prefix is |
| 213 | ``'/usr/local'``. The returned string points into static storage; the caller |
| 214 | should not modify its value. This corresponds to the :makevar:`exec_prefix` |
| 215 | variable in the top-level :file:`Makefile` and the :option:`--exec-prefix` |
| 216 | argument to the :program:`configure` script at build time. The value is |
| 217 | available to Python code as ``sys.exec_prefix``. It is only useful on Unix. |
| 218 | |
| 219 | Background: The exec-prefix differs from the prefix when platform dependent |
| 220 | files (such as executables and shared libraries) are installed in a different |
| 221 | directory tree. In a typical installation, platform dependent files may be |
| 222 | installed in the :file:`/usr/local/plat` subtree while platform independent may |
| 223 | be installed in :file:`/usr/local`. |
| 224 | |
| 225 | Generally speaking, a platform is a combination of hardware and software |
| 226 | families, e.g. Sparc machines running the Solaris 2.x operating system are |
| 227 | considered the same platform, but Intel machines running Solaris 2.x are another |
| 228 | platform, and Intel machines running Linux are yet another platform. Different |
| 229 | major revisions of the same operating system generally also form different |
| 230 | platforms. Non-Unix operating systems are a different story; the installation |
| 231 | strategies on those systems are so different that the prefix and exec-prefix are |
| 232 | meaningless, and set to the empty string. Note that compiled Python bytecode |
| 233 | files are platform independent (but not independent from the Python version by |
| 234 | which they were compiled!). |
| 235 | |
| 236 | System administrators will know how to configure the :program:`mount` or |
| 237 | :program:`automount` programs to share :file:`/usr/local` between platforms |
| 238 | while having :file:`/usr/local/plat` be a different filesystem for each |
| 239 | platform. |
| 240 | |
| 241 | |
| 242 | .. cfunction:: char* Py_GetProgramFullPath() |
| 243 | |
| 244 | .. index:: |
| 245 | single: Py_SetProgramName() |
| 246 | single: executable (in module sys) |
| 247 | |
| 248 | Return the full program name of the Python executable; this is computed as a |
| 249 | side-effect of deriving the default module search path from the program name |
| 250 | (set by :cfunc:`Py_SetProgramName` above). The returned string points into |
| 251 | static storage; the caller should not modify its value. The value is available |
| 252 | to Python code as ``sys.executable``. |
| 253 | |
| 254 | |
| 255 | .. cfunction:: char* Py_GetPath() |
| 256 | |
| 257 | .. index:: |
| 258 | triple: module; search; path |
| 259 | single: path (in module sys) |
| 260 | |
Georg Brandl | 54fd8ae | 2010-01-07 20:54:45 +0000 | [diff] [blame] | 261 | Return the default module search path; this is computed from the program name |
| 262 | (set by :cfunc:`Py_SetProgramName` above) and some environment variables. |
| 263 | The returned string consists of a series of directory names separated by a |
| 264 | platform dependent delimiter character. The delimiter character is ``':'`` |
| 265 | on Unix and Mac OS X, ``';'`` on Windows. The returned string points into |
| 266 | static storage; the caller should not modify its value. The list |
| 267 | :data:`sys.path` is initialized with this value on interpreter startup; it |
| 268 | can be (and usually is) modified later to change the search path for loading |
| 269 | modules. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 270 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 271 | .. XXX should give the exact rules |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 272 | |
| 273 | |
| 274 | .. cfunction:: const char* Py_GetVersion() |
| 275 | |
| 276 | Return the version of this Python interpreter. This is a string that looks |
| 277 | something like :: |
| 278 | |
| 279 | "1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]" |
| 280 | |
| 281 | .. index:: single: version (in module sys) |
| 282 | |
| 283 | The first word (up to the first space character) is the current Python version; |
| 284 | the first three characters are the major and minor version separated by a |
| 285 | period. The returned string points into static storage; the caller should not |
| 286 | modify its value. The value is available to Python code as ``sys.version``. |
| 287 | |
| 288 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 289 | .. cfunction:: const char* Py_GetPlatform() |
| 290 | |
| 291 | .. index:: single: platform (in module sys) |
| 292 | |
| 293 | Return the platform identifier for the current platform. On Unix, this is |
| 294 | formed from the "official" name of the operating system, converted to lower |
| 295 | case, followed by the major revision number; e.g., for Solaris 2.x, which is |
| 296 | also known as SunOS 5.x, the value is ``'sunos5'``. On Mac OS X, it is |
| 297 | ``'darwin'``. On Windows, it is ``'win'``. The returned string points into |
| 298 | static storage; the caller should not modify its value. The value is available |
| 299 | to Python code as ``sys.platform``. |
| 300 | |
| 301 | |
| 302 | .. cfunction:: const char* Py_GetCopyright() |
| 303 | |
| 304 | Return the official copyright string for the current Python version, for example |
| 305 | |
| 306 | ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'`` |
| 307 | |
| 308 | .. index:: single: copyright (in module sys) |
| 309 | |
| 310 | The returned string points into static storage; the caller should not modify its |
| 311 | value. The value is available to Python code as ``sys.copyright``. |
| 312 | |
| 313 | |
| 314 | .. cfunction:: const char* Py_GetCompiler() |
| 315 | |
| 316 | Return an indication of the compiler used to build the current Python version, |
| 317 | in square brackets, for example:: |
| 318 | |
| 319 | "[GCC 2.7.2.2]" |
| 320 | |
| 321 | .. index:: single: version (in module sys) |
| 322 | |
| 323 | The returned string points into static storage; the caller should not modify its |
| 324 | value. The value is available to Python code as part of the variable |
| 325 | ``sys.version``. |
| 326 | |
| 327 | |
| 328 | .. cfunction:: const char* Py_GetBuildInfo() |
| 329 | |
| 330 | Return information about the sequence number and build date and time of the |
| 331 | current Python interpreter instance, for example :: |
| 332 | |
| 333 | "#67, Aug 1 1997, 22:34:28" |
| 334 | |
| 335 | .. index:: single: version (in module sys) |
| 336 | |
| 337 | The returned string points into static storage; the caller should not modify its |
| 338 | value. The value is available to Python code as part of the variable |
| 339 | ``sys.version``. |
| 340 | |
| 341 | |
Antoine Pitrou | 6a26560 | 2010-05-21 17:12:38 +0000 | [diff] [blame] | 342 | .. cfunction:: void PySys_SetArgvEx(int argc, char **argv, int updatepath) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 343 | |
| 344 | .. index:: |
| 345 | single: main() |
| 346 | single: Py_FatalError() |
| 347 | single: argv (in module sys) |
| 348 | |
Georg Brandl | acc802b | 2009-02-05 10:37:07 +0000 | [diff] [blame] | 349 | Set :data:`sys.argv` based on *argc* and *argv*. These parameters are |
| 350 | similar to those passed to the program's :cfunc:`main` function with the |
| 351 | difference that the first entry should refer to the script file to be |
| 352 | executed rather than the executable hosting the Python interpreter. If there |
| 353 | isn't a script that will be run, the first entry in *argv* can be an empty |
| 354 | string. If this function fails to initialize :data:`sys.argv`, a fatal |
| 355 | condition is signalled using :cfunc:`Py_FatalError`. |
| 356 | |
Antoine Pitrou | 6a26560 | 2010-05-21 17:12:38 +0000 | [diff] [blame] | 357 | If *updatepath* is zero, this is all the function does. If *updatepath* |
| 358 | is non-zero, the function also modifies :data:`sys.path` according to the |
| 359 | following algorithm: |
| 360 | |
| 361 | - If the name of an existing script is passed in ``argv[0]``, the absolute |
| 362 | path of the directory where the script is located is prepended to |
| 363 | :data:`sys.path`. |
| 364 | - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point |
| 365 | to an existing file name), an empty string is prepended to |
| 366 | :data:`sys.path`, which is the same as prepending the current working |
| 367 | directory (``"."``). |
| 368 | |
| 369 | .. note:: |
| 370 | It is recommended that applications embedding the Python interpreter |
| 371 | for purposes other than executing a single script pass 0 as *updatepath*, |
| 372 | and update :data:`sys.path` themselves if desired. |
| 373 | See `CVE-2008-5983 <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_. |
| 374 | |
| 375 | On versions before 2.6.6, you can achieve the same effect by manually |
| 376 | popping the first :data:`sys.path` element after having called |
| 377 | :cfunc:`PySys_SetArgv`, for example using:: |
| 378 | |
| 379 | PyRun_SimpleString("import sys; sys.path.pop(0)\n"); |
| 380 | |
| 381 | .. versionadded:: 2.6.6 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 382 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 383 | .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params; |
| 384 | check w/ Guido. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 385 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 386 | |
Antoine Pitrou | 6a26560 | 2010-05-21 17:12:38 +0000 | [diff] [blame] | 387 | .. cfunction:: void PySys_SetArgv(int argc, char **argv) |
| 388 | |
Georg Brandl | 9933da0 | 2010-06-14 15:58:39 +0000 | [diff] [blame] | 389 | This function works like :cfunc:`PySys_SetArgvEx` with *updatepath* set to 1. |
Antoine Pitrou | 6a26560 | 2010-05-21 17:12:38 +0000 | [diff] [blame] | 390 | |
| 391 | |
Georg Brandl | 4400d84 | 2009-02-05 11:32:18 +0000 | [diff] [blame] | 392 | .. cfunction:: void Py_SetPythonHome(char *home) |
| 393 | |
| 394 | Set the default "home" directory, that is, the location of the standard |
| 395 | Python libraries. The libraries are searched in |
| 396 | :file:`{home}/lib/python{version}` and :file:`{home}/lib/python{version}`. |
Benjamin Peterson | ea7120c | 2009-09-15 03:36:26 +0000 | [diff] [blame] | 397 | The argument should point to a zero-terminated character string in static |
| 398 | storage whose contents will not change for the duration of the program's |
| 399 | execution. No code in the Python interpreter will change the contents of |
| 400 | this storage. |
Georg Brandl | 4400d84 | 2009-02-05 11:32:18 +0000 | [diff] [blame] | 401 | |
| 402 | |
| 403 | .. cfunction:: char* Py_GetPythonHome() |
| 404 | |
| 405 | Return the default "home", that is, the value set by a previous call to |
| 406 | :cfunc:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME` |
| 407 | environment variable if it is set. |
| 408 | |
| 409 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 410 | .. _threads: |
| 411 | |
| 412 | Thread State and the Global Interpreter Lock |
| 413 | ============================================ |
| 414 | |
| 415 | .. index:: |
| 416 | single: global interpreter lock |
| 417 | single: interpreter lock |
| 418 | single: lock, interpreter |
| 419 | |
| 420 | The Python interpreter is not fully thread safe. In order to support |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 421 | multi-threaded Python programs, there's a global lock, called the :dfn:`global |
| 422 | interpreter lock` or :dfn:`GIL`, that must be held by the current thread before |
| 423 | it can safely access Python objects. Without the lock, even the simplest |
| 424 | operations could cause problems in a multi-threaded program: for example, when |
| 425 | two threads simultaneously increment the reference count of the same object, the |
| 426 | reference count could end up being incremented only once instead of twice. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 427 | |
| 428 | .. index:: single: setcheckinterval() (in module sys) |
| 429 | |
| 430 | Therefore, the rule exists that only the thread that has acquired the global |
| 431 | interpreter lock may operate on Python objects or call Python/C API functions. |
| 432 | In order to support multi-threaded Python programs, the interpreter regularly |
| 433 | releases and reacquires the lock --- by default, every 100 bytecode instructions |
| 434 | (this can be changed with :func:`sys.setcheckinterval`). The lock is also |
| 435 | released and reacquired around potentially blocking I/O operations like reading |
| 436 | or writing a file, so that other threads can run while the thread that requests |
| 437 | the I/O is waiting for the I/O operation to complete. |
| 438 | |
| 439 | .. index:: |
| 440 | single: PyThreadState |
| 441 | single: PyThreadState |
| 442 | |
| 443 | The Python interpreter needs to keep some bookkeeping information separate per |
| 444 | thread --- for this it uses a data structure called :ctype:`PyThreadState`. |
| 445 | There's one global variable, however: the pointer to the current |
Georg Brandl | 2622b54 | 2009-04-27 17:09:53 +0000 | [diff] [blame] | 446 | :ctype:`PyThreadState` structure. Before the addition of :dfn:`thread-local |
| 447 | storage` (:dfn:`TLS`) the current thread state had to be manipulated |
| 448 | explicitly. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 449 | |
| 450 | This is easy enough in most cases. Most code manipulating the global |
| 451 | interpreter lock has the following simple structure:: |
| 452 | |
| 453 | Save the thread state in a local variable. |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 454 | Release the global interpreter lock. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 455 | ...Do some blocking I/O operation... |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 456 | Reacquire the global interpreter lock. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 457 | Restore the thread state from the local variable. |
| 458 | |
| 459 | This is so common that a pair of macros exists to simplify it:: |
| 460 | |
| 461 | Py_BEGIN_ALLOW_THREADS |
| 462 | ...Do some blocking I/O operation... |
| 463 | Py_END_ALLOW_THREADS |
| 464 | |
| 465 | .. index:: |
| 466 | single: Py_BEGIN_ALLOW_THREADS |
| 467 | single: Py_END_ALLOW_THREADS |
| 468 | |
| 469 | The :cmacro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a |
| 470 | hidden local variable; the :cmacro:`Py_END_ALLOW_THREADS` macro closes the |
| 471 | block. Another advantage of using these two macros is that when Python is |
| 472 | compiled without thread support, they are defined empty, thus saving the thread |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 473 | state and GIL manipulations. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 474 | |
| 475 | When thread support is enabled, the block above expands to the following code:: |
| 476 | |
| 477 | PyThreadState *_save; |
| 478 | |
| 479 | _save = PyEval_SaveThread(); |
| 480 | ...Do some blocking I/O operation... |
| 481 | PyEval_RestoreThread(_save); |
| 482 | |
| 483 | Using even lower level primitives, we can get roughly the same effect as |
| 484 | follows:: |
| 485 | |
| 486 | PyThreadState *_save; |
| 487 | |
| 488 | _save = PyThreadState_Swap(NULL); |
| 489 | PyEval_ReleaseLock(); |
| 490 | ...Do some blocking I/O operation... |
| 491 | PyEval_AcquireLock(); |
| 492 | PyThreadState_Swap(_save); |
| 493 | |
| 494 | .. index:: |
| 495 | single: PyEval_RestoreThread() |
| 496 | single: errno |
| 497 | single: PyEval_SaveThread() |
| 498 | single: PyEval_ReleaseLock() |
| 499 | single: PyEval_AcquireLock() |
| 500 | |
| 501 | There are some subtle differences; in particular, :cfunc:`PyEval_RestoreThread` |
| 502 | saves and restores the value of the global variable :cdata:`errno`, since the |
| 503 | lock manipulation does not guarantee that :cdata:`errno` is left alone. Also, |
| 504 | when thread support is disabled, :cfunc:`PyEval_SaveThread` and |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 505 | :cfunc:`PyEval_RestoreThread` don't manipulate the GIL; in this case, |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 506 | :cfunc:`PyEval_ReleaseLock` and :cfunc:`PyEval_AcquireLock` are not available. |
| 507 | This is done so that dynamically loaded extensions compiled with thread support |
| 508 | enabled can be loaded by an interpreter that was compiled with disabled thread |
| 509 | support. |
| 510 | |
| 511 | The global interpreter lock is used to protect the pointer to the current thread |
| 512 | state. When releasing the lock and saving the thread state, the current thread |
| 513 | state pointer must be retrieved before the lock is released (since another |
| 514 | thread could immediately acquire the lock and store its own thread state in the |
| 515 | global variable). Conversely, when acquiring the lock and restoring the thread |
| 516 | state, the lock must be acquired before storing the thread state pointer. |
| 517 | |
Jeroen Ruigrok van der Werven | 2dcf46e | 2009-04-25 13:07:40 +0000 | [diff] [blame] | 518 | It is important to note that when threads are created from C, they don't have |
| 519 | the global interpreter lock, nor is there a thread state data structure for |
| 520 | them. Such threads must bootstrap themselves into existence, by first |
| 521 | creating a thread state data structure, then acquiring the lock, and finally |
| 522 | storing their thread state pointer, before they can start using the Python/C |
| 523 | API. When they are done, they should reset the thread state pointer, release |
| 524 | the lock, and finally free their thread state data structure. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 525 | |
| 526 | Beginning with version 2.3, threads can now take advantage of the |
| 527 | :cfunc:`PyGILState_\*` functions to do all of the above automatically. The |
| 528 | typical idiom for calling into Python from a C thread is now:: |
| 529 | |
| 530 | PyGILState_STATE gstate; |
| 531 | gstate = PyGILState_Ensure(); |
| 532 | |
| 533 | /* Perform Python actions here. */ |
| 534 | result = CallSomeFunction(); |
| 535 | /* evaluate result */ |
| 536 | |
| 537 | /* Release the thread. No Python API allowed beyond this point. */ |
| 538 | PyGILState_Release(gstate); |
| 539 | |
| 540 | Note that the :cfunc:`PyGILState_\*` functions assume there is only one global |
| 541 | interpreter (created automatically by :cfunc:`Py_Initialize`). Python still |
| 542 | supports the creation of additional interpreters (using |
| 543 | :cfunc:`Py_NewInterpreter`), but mixing multiple interpreters and the |
| 544 | :cfunc:`PyGILState_\*` API is unsupported. |
| 545 | |
Thomas Wouters | c4dcb38 | 2009-09-16 19:55:54 +0000 | [diff] [blame] | 546 | Another important thing to note about threads is their behaviour in the face |
| 547 | of the C :cfunc:`fork` call. On most systems with :cfunc:`fork`, after a |
| 548 | process forks only the thread that issued the fork will exist. That also |
| 549 | means any locks held by other threads will never be released. Python solves |
| 550 | this for :func:`os.fork` by acquiring the locks it uses internally before |
| 551 | the fork, and releasing them afterwards. In addition, it resets any |
| 552 | :ref:`lock-objects` in the child. When extending or embedding Python, there |
| 553 | is no way to inform Python of additional (non-Python) locks that need to be |
| 554 | acquired before or reset after a fork. OS facilities such as |
| 555 | :cfunc:`posix_atfork` would need to be used to accomplish the same thing. |
| 556 | Additionally, when extending or embedding Python, calling :cfunc:`fork` |
| 557 | directly rather than through :func:`os.fork` (and returning to or calling |
| 558 | into Python) may result in a deadlock by one of Python's internal locks |
| 559 | being held by a thread that is defunct after the fork. |
| 560 | :cfunc:`PyOS_AfterFork` tries to reset the necessary locks, but is not |
| 561 | always able to. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 562 | |
| 563 | .. ctype:: PyInterpreterState |
| 564 | |
| 565 | This data structure represents the state shared by a number of cooperating |
| 566 | threads. Threads belonging to the same interpreter share their module |
| 567 | administration and a few other internal items. There are no public members in |
| 568 | this structure. |
| 569 | |
| 570 | Threads belonging to different interpreters initially share nothing, except |
| 571 | process state like available memory, open file descriptors and such. The global |
| 572 | interpreter lock is also shared by all threads, regardless of to which |
| 573 | interpreter they belong. |
| 574 | |
| 575 | |
| 576 | .. ctype:: PyThreadState |
| 577 | |
| 578 | This data structure represents the state of a single thread. The only public |
| 579 | data member is :ctype:`PyInterpreterState \*`:attr:`interp`, which points to |
| 580 | this thread's interpreter state. |
| 581 | |
| 582 | |
| 583 | .. cfunction:: void PyEval_InitThreads() |
| 584 | |
| 585 | .. index:: |
| 586 | single: PyEval_ReleaseLock() |
| 587 | single: PyEval_ReleaseThread() |
| 588 | single: PyEval_SaveThread() |
| 589 | single: PyEval_RestoreThread() |
| 590 | |
| 591 | Initialize and acquire the global interpreter lock. It should be called in the |
| 592 | main thread before creating a second thread or engaging in any other thread |
| 593 | operations such as :cfunc:`PyEval_ReleaseLock` or |
| 594 | ``PyEval_ReleaseThread(tstate)``. It is not needed before calling |
| 595 | :cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_RestoreThread`. |
| 596 | |
| 597 | .. index:: single: Py_Initialize() |
| 598 | |
| 599 | This is a no-op when called for a second time. It is safe to call this function |
| 600 | before calling :cfunc:`Py_Initialize`. |
| 601 | |
| 602 | .. index:: module: thread |
| 603 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 604 | When only the main thread exists, no GIL operations are needed. This is a |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 605 | common situation (most Python programs do not use threads), and the lock |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 606 | operations slow the interpreter down a bit. Therefore, the lock is not |
| 607 | created initially. This situation is equivalent to having acquired the lock: |
| 608 | when there is only a single thread, all object accesses are safe. Therefore, |
| 609 | when this function initializes the global interpreter lock, it also acquires |
| 610 | it. Before the Python :mod:`thread` module creates a new thread, knowing |
| 611 | that either it has the lock or the lock hasn't been created yet, it calls |
| 612 | :cfunc:`PyEval_InitThreads`. When this call returns, it is guaranteed that |
| 613 | the lock has been created and that the calling thread has acquired it. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 614 | |
| 615 | It is **not** safe to call this function when it is unknown which thread (if |
| 616 | any) currently has the global interpreter lock. |
| 617 | |
| 618 | This function is not available when thread support is disabled at compile time. |
| 619 | |
| 620 | |
| 621 | .. cfunction:: int PyEval_ThreadsInitialized() |
| 622 | |
| 623 | Returns a non-zero value if :cfunc:`PyEval_InitThreads` has been called. This |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 624 | function can be called without holding the GIL, and therefore can be used to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 625 | avoid calls to the locking API when running single-threaded. This function is |
| 626 | not available when thread support is disabled at compile time. |
| 627 | |
| 628 | .. versionadded:: 2.4 |
| 629 | |
| 630 | |
| 631 | .. cfunction:: void PyEval_AcquireLock() |
| 632 | |
| 633 | Acquire the global interpreter lock. The lock must have been created earlier. |
| 634 | If this thread already has the lock, a deadlock ensues. This function is not |
| 635 | available when thread support is disabled at compile time. |
| 636 | |
| 637 | |
| 638 | .. cfunction:: void PyEval_ReleaseLock() |
| 639 | |
| 640 | Release the global interpreter lock. The lock must have been created earlier. |
| 641 | This function is not available when thread support is disabled at compile time. |
| 642 | |
| 643 | |
| 644 | .. cfunction:: void PyEval_AcquireThread(PyThreadState *tstate) |
| 645 | |
| 646 | Acquire the global interpreter lock and set the current thread state to |
| 647 | *tstate*, which should not be *NULL*. The lock must have been created earlier. |
| 648 | If this thread already has the lock, deadlock ensues. This function is not |
| 649 | available when thread support is disabled at compile time. |
| 650 | |
| 651 | |
| 652 | .. cfunction:: void PyEval_ReleaseThread(PyThreadState *tstate) |
| 653 | |
| 654 | Reset the current thread state to *NULL* and release the global interpreter |
| 655 | lock. The lock must have been created earlier and must be held by the current |
| 656 | thread. The *tstate* argument, which must not be *NULL*, is only used to check |
| 657 | that it represents the current thread state --- if it isn't, a fatal error is |
| 658 | reported. This function is not available when thread support is disabled at |
| 659 | compile time. |
| 660 | |
| 661 | |
| 662 | .. cfunction:: PyThreadState* PyEval_SaveThread() |
| 663 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 664 | Release the global interpreter lock (if it has been created and thread |
| 665 | support is enabled) and reset the thread state to *NULL*, returning the |
| 666 | previous thread state (which is not *NULL*). If the lock has been created, |
| 667 | the current thread must have acquired it. (This function is available even |
| 668 | when thread support is disabled at compile time.) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 669 | |
| 670 | |
| 671 | .. cfunction:: void PyEval_RestoreThread(PyThreadState *tstate) |
| 672 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 673 | Acquire the global interpreter lock (if it has been created and thread |
| 674 | support is enabled) and set the thread state to *tstate*, which must not be |
| 675 | *NULL*. If the lock has been created, the current thread must not have |
| 676 | acquired it, otherwise deadlock ensues. (This function is available even |
| 677 | when thread support is disabled at compile time.) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 678 | |
Georg Brandl | 16f1df9 | 2007-12-01 22:24:47 +0000 | [diff] [blame] | 679 | |
| 680 | .. cfunction:: void PyEval_ReInitThreads() |
| 681 | |
| 682 | This function is called from :cfunc:`PyOS_AfterFork` to ensure that newly |
| 683 | created child processes don't hold locks referring to threads which |
| 684 | are not running in the child process. |
| 685 | |
| 686 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 687 | The following macros are normally used without a trailing semicolon; look for |
| 688 | example usage in the Python source distribution. |
| 689 | |
| 690 | |
| 691 | .. cmacro:: Py_BEGIN_ALLOW_THREADS |
| 692 | |
| 693 | This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``. |
| 694 | Note that it contains an opening brace; it must be matched with a following |
| 695 | :cmacro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this |
| 696 | macro. It is a no-op when thread support is disabled at compile time. |
| 697 | |
| 698 | |
| 699 | .. cmacro:: Py_END_ALLOW_THREADS |
| 700 | |
| 701 | This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains |
| 702 | a closing brace; it must be matched with an earlier |
| 703 | :cmacro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of |
| 704 | this macro. It is a no-op when thread support is disabled at compile time. |
| 705 | |
| 706 | |
| 707 | .. cmacro:: Py_BLOCK_THREADS |
| 708 | |
| 709 | This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to |
| 710 | :cmacro:`Py_END_ALLOW_THREADS` without the closing brace. It is a no-op when |
| 711 | thread support is disabled at compile time. |
| 712 | |
| 713 | |
| 714 | .. cmacro:: Py_UNBLOCK_THREADS |
| 715 | |
| 716 | This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to |
| 717 | :cmacro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable |
| 718 | declaration. It is a no-op when thread support is disabled at compile time. |
| 719 | |
| 720 | All of the following functions are only available when thread support is enabled |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 721 | at compile time, and must be called only when the global interpreter lock has |
| 722 | been created. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 723 | |
| 724 | |
| 725 | .. cfunction:: PyInterpreterState* PyInterpreterState_New() |
| 726 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 727 | Create a new interpreter state object. The global interpreter lock need not |
| 728 | be held, but may be held if it is necessary to serialize calls to this |
| 729 | function. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 730 | |
| 731 | |
| 732 | .. cfunction:: void PyInterpreterState_Clear(PyInterpreterState *interp) |
| 733 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 734 | Reset all information in an interpreter state object. The global interpreter |
| 735 | lock must be held. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 736 | |
| 737 | |
| 738 | .. cfunction:: void PyInterpreterState_Delete(PyInterpreterState *interp) |
| 739 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 740 | Destroy an interpreter state object. The global interpreter lock need not be |
| 741 | held. The interpreter state must have been reset with a previous call to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 742 | :cfunc:`PyInterpreterState_Clear`. |
| 743 | |
| 744 | |
| 745 | .. cfunction:: PyThreadState* PyThreadState_New(PyInterpreterState *interp) |
| 746 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 747 | Create a new thread state object belonging to the given interpreter object. |
| 748 | The global interpreter lock need not be held, but may be held if it is |
| 749 | necessary to serialize calls to this function. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 750 | |
| 751 | |
| 752 | .. cfunction:: void PyThreadState_Clear(PyThreadState *tstate) |
| 753 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 754 | Reset all information in a thread state object. The global interpreter lock |
| 755 | must be held. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 756 | |
| 757 | |
| 758 | .. cfunction:: void PyThreadState_Delete(PyThreadState *tstate) |
| 759 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 760 | Destroy a thread state object. The global interpreter lock need not be held. |
| 761 | The thread state must have been reset with a previous call to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 762 | :cfunc:`PyThreadState_Clear`. |
| 763 | |
| 764 | |
| 765 | .. cfunction:: PyThreadState* PyThreadState_Get() |
| 766 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 767 | Return the current thread state. The global interpreter lock must be held. |
| 768 | When the current thread state is *NULL*, this issues a fatal error (so that |
| 769 | the caller needn't check for *NULL*). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 770 | |
| 771 | |
| 772 | .. cfunction:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate) |
| 773 | |
| 774 | Swap the current thread state with the thread state given by the argument |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 775 | *tstate*, which may be *NULL*. The global interpreter lock must be held. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 776 | |
| 777 | |
| 778 | .. cfunction:: PyObject* PyThreadState_GetDict() |
| 779 | |
| 780 | Return a dictionary in which extensions can store thread-specific state |
| 781 | information. Each extension should use a unique key to use to store state in |
| 782 | the dictionary. It is okay to call this function when no current thread state |
| 783 | is available. If this function returns *NULL*, no exception has been raised and |
| 784 | the caller should assume no current thread state is available. |
| 785 | |
| 786 | .. versionchanged:: 2.3 |
| 787 | Previously this could only be called when a current thread is active, and *NULL* |
| 788 | meant that an exception was raised. |
| 789 | |
| 790 | |
| 791 | .. cfunction:: int PyThreadState_SetAsyncExc(long id, PyObject *exc) |
| 792 | |
| 793 | Asynchronously raise an exception in a thread. The *id* argument is the thread |
| 794 | id of the target thread; *exc* is the exception object to be raised. This |
| 795 | function does not steal any references to *exc*. To prevent naive misuse, you |
| 796 | must write your own C extension to call this. Must be called with the GIL held. |
| 797 | Returns the number of thread states modified; this is normally one, but will be |
| 798 | zero if the thread id isn't found. If *exc* is :const:`NULL`, the pending |
| 799 | exception (if any) for the thread is cleared. This raises no exceptions. |
| 800 | |
| 801 | .. versionadded:: 2.3 |
| 802 | |
| 803 | |
| 804 | .. cfunction:: PyGILState_STATE PyGILState_Ensure() |
| 805 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 806 | Ensure that the current thread is ready to call the Python C API regardless |
| 807 | of the current state of Python, or of the global interpreter lock. This may |
| 808 | be called as many times as desired by a thread as long as each call is |
| 809 | matched with a call to :cfunc:`PyGILState_Release`. In general, other |
| 810 | thread-related APIs may be used between :cfunc:`PyGILState_Ensure` and |
| 811 | :cfunc:`PyGILState_Release` calls as long as the thread state is restored to |
| 812 | its previous state before the Release(). For example, normal usage of the |
| 813 | :cmacro:`Py_BEGIN_ALLOW_THREADS` and :cmacro:`Py_END_ALLOW_THREADS` macros is |
| 814 | acceptable. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 815 | |
| 816 | The return value is an opaque "handle" to the thread state when |
Benjamin Peterson | 9d1e2cd | 2008-10-10 22:23:41 +0000 | [diff] [blame] | 817 | :cfunc:`PyGILState_Ensure` was called, and must be passed to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 818 | :cfunc:`PyGILState_Release` to ensure Python is left in the same state. Even |
| 819 | though recursive calls are allowed, these handles *cannot* be shared - each |
Benjamin Peterson | 9d1e2cd | 2008-10-10 22:23:41 +0000 | [diff] [blame] | 820 | unique call to :cfunc:`PyGILState_Ensure` must save the handle for its call |
| 821 | to :cfunc:`PyGILState_Release`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 822 | |
| 823 | When the function returns, the current thread will hold the GIL. Failure is a |
| 824 | fatal error. |
| 825 | |
| 826 | .. versionadded:: 2.3 |
| 827 | |
| 828 | |
| 829 | .. cfunction:: void PyGILState_Release(PyGILState_STATE) |
| 830 | |
| 831 | Release any resources previously acquired. After this call, Python's state will |
| 832 | be the same as it was prior to the corresponding :cfunc:`PyGILState_Ensure` call |
| 833 | (but generally this state will be unknown to the caller, hence the use of the |
| 834 | GILState API.) |
| 835 | |
| 836 | Every call to :cfunc:`PyGILState_Ensure` must be matched by a call to |
| 837 | :cfunc:`PyGILState_Release` on the same thread. |
| 838 | |
| 839 | .. versionadded:: 2.3 |
| 840 | |
| 841 | |
Kristján Valur Jónsson | 0e2d8c3 | 2009-01-09 21:35:16 +0000 | [diff] [blame] | 842 | |
| 843 | Asynchronous Notifications |
| 844 | ========================== |
| 845 | |
Andrew M. Kuchling | a178a69 | 2009-04-03 21:45:29 +0000 | [diff] [blame] | 846 | A mechanism is provided to make asynchronous notifications to the main |
Kristján Valur Jónsson | 0e2d8c3 | 2009-01-09 21:35:16 +0000 | [diff] [blame] | 847 | interpreter thread. These notifications take the form of a function |
| 848 | pointer and a void argument. |
| 849 | |
| 850 | .. index:: single: setcheckinterval() (in module sys) |
| 851 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 852 | Every check interval, when the global interpreter lock is released and |
Ezio Melotti | 062d2b5 | 2009-12-19 22:41:49 +0000 | [diff] [blame] | 853 | reacquired, Python will also call any such provided functions. This can be used |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 854 | for example by asynchronous IO handlers. The notification can be scheduled from |
| 855 | a worker thread and the actual call than made at the earliest convenience by the |
| 856 | main thread where it has possession of the global interpreter lock and can |
| 857 | perform any Python API calls. |
Kristján Valur Jónsson | 0e2d8c3 | 2009-01-09 21:35:16 +0000 | [diff] [blame] | 858 | |
Georg Brandl | dd958e0 | 2009-01-13 08:11:07 +0000 | [diff] [blame] | 859 | .. cfunction:: void Py_AddPendingCall( int (*func)(void *, void *arg) ) |
Kristján Valur Jónsson | 0e2d8c3 | 2009-01-09 21:35:16 +0000 | [diff] [blame] | 860 | |
| 861 | .. index:: single: Py_AddPendingCall() |
| 862 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 863 | Post a notification to the Python main thread. If successful, *func* will be |
| 864 | called with the argument *arg* at the earliest convenience. *func* will be |
| 865 | called having the global interpreter lock held and can thus use the full |
| 866 | Python API and can take any action such as setting object attributes to |
| 867 | signal IO completion. It must return 0 on success, or -1 signalling an |
| 868 | exception. The notification function won't be interrupted to perform another |
| 869 | asynchronous notification recursively, but it can still be interrupted to |
| 870 | switch threads if the global interpreter lock is released, for example, if it |
Ezio Melotti | 062d2b5 | 2009-12-19 22:41:49 +0000 | [diff] [blame] | 871 | calls back into Python code. |
Kristján Valur Jónsson | 0e2d8c3 | 2009-01-09 21:35:16 +0000 | [diff] [blame] | 872 | |
| 873 | This function returns 0 on success in which case the notification has been |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 874 | scheduled. Otherwise, for example if the notification buffer is full, it |
| 875 | returns -1 without setting any exception. |
Kristján Valur Jónsson | 0e2d8c3 | 2009-01-09 21:35:16 +0000 | [diff] [blame] | 876 | |
Georg Brandl | 1ede0d6 | 2009-04-05 17:17:42 +0000 | [diff] [blame] | 877 | This function can be called on any thread, be it a Python thread or some |
| 878 | other system thread. If it is a Python thread, it doesn't matter if it holds |
| 879 | the global interpreter lock or not. |
Kristján Valur Jónsson | 0e2d8c3 | 2009-01-09 21:35:16 +0000 | [diff] [blame] | 880 | |
| 881 | .. versionadded:: 2.7 |
| 882 | |
| 883 | |
| 884 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 885 | .. _profiling: |
| 886 | |
| 887 | Profiling and Tracing |
| 888 | ===================== |
| 889 | |
| 890 | .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> |
| 891 | |
| 892 | |
| 893 | The Python interpreter provides some low-level support for attaching profiling |
| 894 | and execution tracing facilities. These are used for profiling, debugging, and |
| 895 | coverage analysis tools. |
| 896 | |
| 897 | Starting with Python 2.2, the implementation of this facility was substantially |
| 898 | revised, and an interface from C was added. This C interface allows the |
| 899 | profiling or tracing code to avoid the overhead of calling through Python-level |
| 900 | callable objects, making a direct C function call instead. The essential |
| 901 | attributes of the facility have not changed; the interface allows trace |
| 902 | functions to be installed per-thread, and the basic events reported to the trace |
| 903 | function are the same as had been reported to the Python-level trace functions |
| 904 | in previous versions. |
| 905 | |
| 906 | |
| 907 | .. ctype:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg) |
| 908 | |
| 909 | The type of the trace function registered using :cfunc:`PyEval_SetProfile` and |
| 910 | :cfunc:`PyEval_SetTrace`. The first parameter is the object passed to the |
| 911 | registration function as *obj*, *frame* is the frame object to which the event |
| 912 | pertains, *what* is one of the constants :const:`PyTrace_CALL`, |
| 913 | :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`, |
| 914 | :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, or |
| 915 | :const:`PyTrace_C_RETURN`, and *arg* depends on the value of *what*: |
| 916 | |
| 917 | +------------------------------+--------------------------------------+ |
| 918 | | Value of *what* | Meaning of *arg* | |
| 919 | +==============================+======================================+ |
| 920 | | :const:`PyTrace_CALL` | Always *NULL*. | |
| 921 | +------------------------------+--------------------------------------+ |
| 922 | | :const:`PyTrace_EXCEPTION` | Exception information as returned by | |
| 923 | | | :func:`sys.exc_info`. | |
| 924 | +------------------------------+--------------------------------------+ |
| 925 | | :const:`PyTrace_LINE` | Always *NULL*. | |
| 926 | +------------------------------+--------------------------------------+ |
| 927 | | :const:`PyTrace_RETURN` | Value being returned to the caller. | |
| 928 | +------------------------------+--------------------------------------+ |
| 929 | | :const:`PyTrace_C_CALL` | Name of function being called. | |
| 930 | +------------------------------+--------------------------------------+ |
| 931 | | :const:`PyTrace_C_EXCEPTION` | Always *NULL*. | |
| 932 | +------------------------------+--------------------------------------+ |
| 933 | | :const:`PyTrace_C_RETURN` | Always *NULL*. | |
| 934 | +------------------------------+--------------------------------------+ |
| 935 | |
| 936 | |
| 937 | .. cvar:: int PyTrace_CALL |
| 938 | |
| 939 | The value of the *what* parameter to a :ctype:`Py_tracefunc` function when a new |
| 940 | call to a function or method is being reported, or a new entry into a generator. |
| 941 | Note that the creation of the iterator for a generator function is not reported |
| 942 | as there is no control transfer to the Python bytecode in the corresponding |
| 943 | frame. |
| 944 | |
| 945 | |
| 946 | .. cvar:: int PyTrace_EXCEPTION |
| 947 | |
| 948 | The value of the *what* parameter to a :ctype:`Py_tracefunc` function when an |
| 949 | exception has been raised. The callback function is called with this value for |
| 950 | *what* when after any bytecode is processed after which the exception becomes |
| 951 | set within the frame being executed. The effect of this is that as exception |
| 952 | propagation causes the Python stack to unwind, the callback is called upon |
| 953 | return to each frame as the exception propagates. Only trace functions receives |
| 954 | these events; they are not needed by the profiler. |
| 955 | |
| 956 | |
| 957 | .. cvar:: int PyTrace_LINE |
| 958 | |
| 959 | The value passed as the *what* parameter to a trace function (but not a |
| 960 | profiling function) when a line-number event is being reported. |
| 961 | |
| 962 | |
| 963 | .. cvar:: int PyTrace_RETURN |
| 964 | |
| 965 | The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a |
| 966 | call is returning without propagating an exception. |
| 967 | |
| 968 | |
| 969 | .. cvar:: int PyTrace_C_CALL |
| 970 | |
| 971 | The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C |
| 972 | function is about to be called. |
| 973 | |
| 974 | |
| 975 | .. cvar:: int PyTrace_C_EXCEPTION |
| 976 | |
| 977 | The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C |
| 978 | function has thrown an exception. |
| 979 | |
| 980 | |
| 981 | .. cvar:: int PyTrace_C_RETURN |
| 982 | |
| 983 | The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C |
| 984 | function has returned. |
| 985 | |
| 986 | |
| 987 | .. cfunction:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj) |
| 988 | |
| 989 | Set the profiler function to *func*. The *obj* parameter is passed to the |
| 990 | function as its first parameter, and may be any Python object, or *NULL*. If |
| 991 | the profile function needs to maintain state, using a different value for *obj* |
| 992 | for each thread provides a convenient and thread-safe place to store it. The |
| 993 | profile function is called for all monitored events except the line-number |
| 994 | events. |
| 995 | |
| 996 | |
| 997 | .. cfunction:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj) |
| 998 | |
| 999 | Set the tracing function to *func*. This is similar to |
| 1000 | :cfunc:`PyEval_SetProfile`, except the tracing function does receive line-number |
| 1001 | events. |
| 1002 | |
Georg Brandl | 16f1df9 | 2007-12-01 22:24:47 +0000 | [diff] [blame] | 1003 | .. cfunction:: PyObject* PyEval_GetCallStats(PyObject *self) |
| 1004 | |
| 1005 | Return a tuple of function call counts. There are constants defined for the |
| 1006 | positions within the tuple: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1007 | |
Georg Brandl | 16f1df9 | 2007-12-01 22:24:47 +0000 | [diff] [blame] | 1008 | +-------------------------------+-------+ |
| 1009 | | Name | Value | |
| 1010 | +===============================+=======+ |
| 1011 | | :const:`PCALL_ALL` | 0 | |
| 1012 | +-------------------------------+-------+ |
| 1013 | | :const:`PCALL_FUNCTION` | 1 | |
| 1014 | +-------------------------------+-------+ |
| 1015 | | :const:`PCALL_FAST_FUNCTION` | 2 | |
| 1016 | +-------------------------------+-------+ |
| 1017 | | :const:`PCALL_FASTER_FUNCTION`| 3 | |
| 1018 | +-------------------------------+-------+ |
| 1019 | | :const:`PCALL_METHOD` | 4 | |
| 1020 | +-------------------------------+-------+ |
| 1021 | | :const:`PCALL_BOUND_METHOD` | 5 | |
| 1022 | +-------------------------------+-------+ |
| 1023 | | :const:`PCALL_CFUNCTION` | 6 | |
| 1024 | +-------------------------------+-------+ |
| 1025 | | :const:`PCALL_TYPE` | 7 | |
| 1026 | +-------------------------------+-------+ |
| 1027 | | :const:`PCALL_GENERATOR` | 8 | |
| 1028 | +-------------------------------+-------+ |
| 1029 | | :const:`PCALL_OTHER` | 9 | |
| 1030 | +-------------------------------+-------+ |
| 1031 | | :const:`PCALL_POP` | 10 | |
| 1032 | +-------------------------------+-------+ |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1033 | |
Georg Brandl | 16f1df9 | 2007-12-01 22:24:47 +0000 | [diff] [blame] | 1034 | :const:`PCALL_FAST_FUNCTION` means no argument tuple needs to be created. |
| 1035 | :const:`PCALL_FASTER_FUNCTION` means that the fast-path frame setup code is used. |
| 1036 | |
| 1037 | If there is a method call where the call can be optimized by changing |
| 1038 | the argument tuple and calling the function directly, it gets recorded |
| 1039 | twice. |
| 1040 | |
| 1041 | This function is only present if Python is compiled with :const:`CALL_PROFILE` |
| 1042 | defined. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1043 | |
| 1044 | .. _advanced-debugging: |
| 1045 | |
| 1046 | Advanced Debugger Support |
| 1047 | ========================= |
| 1048 | |
| 1049 | .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> |
| 1050 | |
| 1051 | |
| 1052 | These functions are only intended to be used by advanced debugging tools. |
| 1053 | |
| 1054 | |
| 1055 | .. cfunction:: PyInterpreterState* PyInterpreterState_Head() |
| 1056 | |
| 1057 | Return the interpreter state object at the head of the list of all such objects. |
| 1058 | |
| 1059 | .. versionadded:: 2.2 |
| 1060 | |
| 1061 | |
| 1062 | .. cfunction:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp) |
| 1063 | |
| 1064 | Return the next interpreter state object after *interp* from the list of all |
| 1065 | such objects. |
| 1066 | |
| 1067 | .. versionadded:: 2.2 |
| 1068 | |
| 1069 | |
| 1070 | .. cfunction:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) |
| 1071 | |
| 1072 | Return the a pointer to the first :ctype:`PyThreadState` object in the list of |
| 1073 | threads associated with the interpreter *interp*. |
| 1074 | |
| 1075 | .. versionadded:: 2.2 |
| 1076 | |
| 1077 | |
| 1078 | .. cfunction:: PyThreadState* PyThreadState_Next(PyThreadState *tstate) |
| 1079 | |
| 1080 | Return the next thread state object after *tstate* from the list of all such |
| 1081 | objects belonging to the same :ctype:`PyInterpreterState` object. |
| 1082 | |
| 1083 | .. versionadded:: 2.2 |
| 1084 | |