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