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