Inicialización, finalización e hilos
************************************

See Python Initialization Configuration for details on how to
configure the interpreter prior to initialization.


Antes de la inicialización de Python
====================================

En una aplicación que incorpora Python, se debe llamar a la función
"Py_Initialize()" antes de usar cualquier otra función de API
Python/C; con la excepción de algunas funciones y variables de
configuración global.

Las siguientes funciones se pueden invocar de forma segura antes de
que se inicializa Python:

* Functions that initialize the interpreter:

  * "Py_Initialize()"

  * "Py_InitializeEx()"

  * "Py_InitializeFromConfig()"

  * "Py_BytesMain()"

  * "Py_Main()"

  * the runtime pre-initialization functions covered in Configuración
    de inicialización de Python

* Funciones de configuración:

  * "PyImport_AppendInittab()"

  * "PyImport_ExtendInittab()"

  * "PyInitFrozenExtensions()"

  * "PyMem_SetAllocator()"

  * "PyMem_SetupDebugHooks()"

  * "PyObject_SetArenaAllocator()"

  * "Py_SetProgramName()"

  * "Py_SetPythonHome()"

  * "PySys_ResetWarnOptions()"

  * the configuration functions covered in Configuración de
    inicialización de Python

* Funciones informativas:

  * "Py_IsInitialized()"

  * "PyMem_GetAllocator()"

  * "PyObject_GetArenaAllocator()"

  * "Py_GetBuildInfo()"

  * "Py_GetCompiler()"

  * "Py_GetCopyright()"

  * "Py_GetPlatform()"

  * "Py_GetVersion()"

  * "Py_IsInitialized()"

* Utilidades:

  * "Py_DecodeLocale()"

  * the status reporting and utility functions covered in
    Configuración de inicialización de Python

* Asignadores de memoria:

  * "PyMem_RawMalloc()"

  * "PyMem_RawRealloc()"

  * "PyMem_RawCalloc()"

  * "PyMem_RawFree()"

* Sincronización:

  * "PyMutex_Lock()"

  * "PyMutex_Unlock()"

Nota:

  Despite their apparent similarity to some of the functions listed
  above, the following functions **should not be called** before the
  interpreter has been initialized: "Py_EncodeLocale()",
  "Py_GetPath()", "Py_GetPrefix()", "Py_GetExecPrefix()",
  "Py_GetProgramFullPath()", "Py_GetPythonHome()",
  "Py_GetProgramName()", "PyEval_InitThreads()", and "Py_RunMain()".


Variables de configuración global
=================================

Python tiene variables para la configuración global para controlar
diferentes características y opciones. De forma predeterminada, estos
indicadores están controlados por opciones de línea de comando.

Cuando una opción establece un indicador, el valor del indicador es la
cantidad de veces que se configuró la opción. Por ejemplo, "-b"
establece "Py_BytesWarningFlag" en 1 y "-bb" establece
"Py_BytesWarningFlag" en 2.

int Py_BytesWarningFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.bytes_warning" en su
   lugar, consulte Python Initialization Configuration.

   Emite una advertencia al comparar "bytes" o "bytearray" con "str" o
   "bytes" con "int". Emite un error si es mayor o igual a "2".

   Establecido por la opción "-b".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_DebugFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.parser_debug" en su
   lugar, consulte Python Initialization Configuration.

   Activa la salida de depuración del analizador (solo para expertos,
   según las opciones de compilación).

   Establecido por la opción "-d" y la variable de entorno
   "PYTHONDEBUG".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_DontWriteBytecodeFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.write_bytecode" en su
   lugar, consulte Python Initialization Configuration.

   Si se establece en un valor distinto de cero, Python no intentará
   escribir archivos ".pyc" en la importación de módulos fuente.

   Establecido por la opción "-B" y la variable de entorno
   "PYTHONDONTWRITEBYTECODE".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_FrozenFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.pathconfig_warnings" en
   su lugar, consulte Python Initialization Configuration.

   Suprime los mensajes de error al calcular la ruta de búsqueda del
   módulo en "Py_GetPath()".

   Indicador privado utilizado por los programas "_freeze_module" y
   "frozenmain".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_HashRandomizationFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se deben utilizar las configuraciones "PyConfig.hash_seed" y
   "PyConfig.use_hash_seed" en su lugar, consulte Python
   Initialization Configuration.

   Se establece en "1" si la variable de entorno "PYTHONHASHSEED" se
   establece en una cadena de caracteres no vacía.

   Si el indicador no es cero, lee la variable de entorno
   "PYTHONHASHSEED" para inicializar la semilla de *hash* secreta.

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_IgnoreEnvironmentFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.use_environment" en su
   lugar, consulte Python Initialization Configuration.

   Ignore todas las variables de entorno "PYTHON*", por ejemplo,
   "PYTHONPATH" y "PYTHONHOME", que puedan estar configuradas.

   Establecido por las opciones "-E" y "-I".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_InspectFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.inspect" en su lugar,
   consulte Python Initialization Configuration.

   Cuando se pasa una secuencia de comandos (*script*) como primer
   argumento o se usa la opción "-c", ingresa al modo interactivo
   después de ejecutar la secuencia de comandos o el comando, incluso
   cuando "sys.stdin" no parece ser un terminal.

   Establecido por la opción "-i" y la variable de entorno
   "PYTHONINSPECT".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_InteractiveFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.interactive" en su
   lugar, consulte Python Initialization Configuration.

   Establecido por la opción "-i".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_IsolatedFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.isolated" en su lugar,
   consulte Python Initialization Configuration.

   Ejecuta Python en modo aislado. En modo aislado "sys.path" no
   contiene ni el directorio de la secuencia de comandos (*script*) ni
   el directorio de paquetes del sitio del usuario (*site-pacages*).

   Establecido por la opción "-I".

   Added in version 3.4.

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_LegacyWindowsFSEncodingFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración
   "PyPreConfig.legacy_windows_fs_encoding" en su lugar, consulte
   Python Initialization Configuration.

   Si la bandera no es cero, utilice la codificación "mbcs" con el
   gestor de errores "replace" en lugar de la codificación UTF-8 con
   el gestor de error "surrogatepass", para la *filesystem encoding
   and error handler* (codificación del sistema de archivos y gestor
   de errores).

   Establece en "1" si la variable de entorno
   "PYTHONLEGACYWINDOWSFSENCODING" está configurada en una cadena de
   caracteres no vacía.

   Ver **PEP 529** para más detalles.

   Availability: Windows.

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_LegacyWindowsStdioFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.legacy_windows_stdio"
   en su lugar, consulte Python Initialization Configuration.

   Si el indicador no es cero, utilice "io.FileIO" en lugar de
   "io._WindowsConsoleIO" para las transmisiones estándar "sys".

   Establece en "1" si la variable de entorno
   "PYTHONLEGACYWINDOWSSTDIO" está configurada en una cadena de
   caracteres no vacía.

   Ver **PEP 528** para más detalles.

   Availability: Windows.

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_NoSiteFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.site_import" en su
   lugar, consulte Python Initialization Configuration.

   Deshabilita la importación del módulo "site" y las manipulaciones
   dependientes del sitio de "sys.path" que conlleva. También
   deshabilita estas manipulaciones si "site" se importa
   explícitamente más tarde (llama a "site.main()" si desea que se
   activen).

   Establecido por la opción "-S".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_NoUserSiteDirectory

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.user_site_directory" en
   su lugar, consulte Configuración de inicialización de Python.

   No agregue el "directorio de paquetes de sitio del usuario" (*site-
   packages*) a "sys.path".

   Establecido por las opciones "-s" y "-I", y la variable de entorno
   "PYTHONNOUSERSITE".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_OptimizeFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.optimization_level" en
   su lugar, consulte Python Initialization Configuration.

   Establecido por la opción "-O" y la variable de entorno
   "PYTHONOPTIMIZE".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_QuietFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.quiet" en su lugar,
   consulte Python Initialization Configuration.

   No muestre los mensajes de *copyright* y de versión incluso en modo
   interactivo.

   Establecido por la opción "-q".

   Added in version 3.2.

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_UnbufferedStdioFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.buffered_stdio" en su
   lugar, consulte Python Initialization Configuration.

   Obliga a las secuencias *stdout* y *stderr* a que no tengan búfer.

   Establecido por la opción "-u" y la variable de entorno
   "PYTHONUNBUFFERED".

   Deprecated since version 3.12, will be removed in version 3.15.

int Py_VerboseFlag

   Esta API se mantiene por compatibilidad con versiones anteriores:
   se debe utilizar la configuración "PyConfig.verbose" en su lugar,
   consulte Python Initialization Configuration.

   Imprime un mensaje cada vez que se inicializa un módulo, mostrando
   el lugar (nombre de archivo o módulo incorporado) desde el que se
   carga. Si es mayor o igual a "2", imprime un mensaje para cada
   archivo que se verifica al buscar un módulo. También proporciona
   información sobre la limpieza del módulo a la salida.

   Establecido por la opción "-v" y la variable de entorno
   "PYTHONVERBOSE".

   Deprecated since version 3.12, will be removed in version 3.15.


Inicializando y finalizando el intérprete
=========================================

void Py_Initialize()
    * Part of the Stable ABI.*

   Inicializa el intérprete de Python. En una aplicación que incorpora
   Python, se debe llamar antes de usar cualquier otra función de API
   Python/C; vea Antes de la inicialización de Python para ver algunas
   excepciones.

   This initializes the table of loaded modules ("sys.modules"), and
   creates the fundamental modules "builtins", "__main__" and "sys".
   It also initializes the module search path ("sys.path"). It does
   not set "sys.argv"; use the Python Initialization Configuration API
   for that. This is a no-op when called for a second time (without
   calling "Py_FinalizeEx()" first).  There is no return value; it is
   a fatal error if the initialization fails.

   Use "Py_InitializeFromConfig()" to customize the Python
   Initialization Configuration.

   Nota:

     En Windows, cambia el modo de consola de "O_TEXT" a "O_BINARY",
     lo que también afectará los usos de la consola que no sean de
     Python utilizando C *Runtime*.

void Py_InitializeEx(int initsigs)
    * Part of the Stable ABI.*

   This function works like "Py_Initialize()" if *initsigs* is "1". If
   *initsigs* is "0", it skips initialization registration of signal
   handlers, which may be useful when CPython is embedded as part of a
   larger application.

   Use "Py_InitializeFromConfig()" to customize the Python
   Initialization Configuration.

PyStatus Py_InitializeFromConfig(const PyConfig *config)

   Initialize Python from *config* configuration, as described in
   Inicialización con PyConfig.

   See the Configuración de inicialización de Python section for
   details on pre-initializing the interpreter, populating the runtime
   configuration structure, and querying the returned status
   structure.

int Py_IsInitialized()
    * Part of the Stable ABI.*

   Retorna verdadero (distinto de cero) cuando el intérprete de Python
   se ha inicializado, falso (cero) si no. Después de que se llama a
   "Py_FinalizeEx()", esto retorna falso hasta que "Py_Initialize()"
   se llama de nuevo.

int Py_IsFinalizing()
    * Part of the Stable ABI since version 3.13.*

   Devuelve verdadero (distinto de cero) si el intérprete principal de
   Python es *shutting down*. Devuelve falso (cero) en caso contrario.

   Added in version 3.13.

int Py_FinalizeEx()
    * Part of the Stable ABI since version 3.6.*

   Undo all initializations made by "Py_Initialize()" and subsequent
   use of Python/C API functions, and destroy all sub-interpreters
   (see "Py_NewInterpreter()" below) that were created and not yet
   destroyed since the last call to "Py_Initialize()".  This is a no-
   op when called for a second time (without calling "Py_Initialize()"
   again first).

   Dado que se trata del proceso inverso de "Py_Initialize()", se debe
   llamar en el mismo subproceso con el mismo intérprete activo, es
   decir, el subproceso principal y el intérprete principal. Nunca se
   debe llamar mientras se esté ejecutando "Py_RunMain()".

   Normalmente, el valor de retorno es "0". Si se produjeron errores
   durante la finalización (limpieza de datos almacenados en búfer),
   se devuelve "-1".

   Note that Python will do a best effort at freeing all memory
   allocated by the Python interpreter.  Therefore, any C-Extension
   should make sure to correctly clean up all of the preveiously
   allocated PyObjects before using them in subsequent calls to
   "Py_Initialize()".  Otherwise it could introduce vulnerabilities
   and incorrect behavior.

   Esta función se proporciona por varias razones. Una aplicación de
   incrustación puede querer reiniciar Python sin tener que reiniciar
   la aplicación misma. Una aplicación que ha cargado el intérprete de
   Python desde una biblioteca cargable dinámicamente (o DLL) puede
   querer liberar toda la memoria asignada por Python antes de
   descargar la DLL. Durante una búsqueda de pérdidas de memoria en
   una aplicación, un desarrollador puede querer liberar toda la
   memoria asignada por Python antes de salir de la aplicación.

   **Bugs and caveats:** The destruction of modules and objects in
   modules is done in random order; this may cause destructors
   ("__del__()" methods) to fail when they depend on other objects
   (even functions) or modules.  Dynamically loaded extension modules
   loaded by Python are not unloaded.  Small amounts of memory
   allocated by the Python interpreter may not be freed (if you find a
   leak, please report it).  Memory tied up in circular references
   between objects is not freed.  Interned strings will all be
   deallocated regardless of their reference count. Some memory
   allocated by extension modules may not be freed.  Some extensions
   may not work properly if their initialization routine is called
   more than once; this can happen if an application calls
   "Py_Initialize()" and "Py_FinalizeEx()" more than once.
   "Py_FinalizeEx()" must not be called recursively from within
   itself.  Therefore, it must not be called by any code that may be
   run as part of the interpreter shutdown process, such as "atexit"
   handlers, object finalizers, or any code that may be run while
   flushing the stdout and stderr files.

   Genera un evento de auditoría "cpython._PySys_ClearAuditHooks" sin
   argumentos.

   Added in version 3.6.

void Py_Finalize()
    * Part of the Stable ABI.*

   Esta es una versión compatible con versiones anteriores de
   "Py_FinalizeEx()" que ignora el valor de retorno.

int Py_BytesMain(int argc, char **argv)
    * Part of the Stable ABI since version 3.8.*

   Similar to "Py_Main()" but *argv* is an array of bytes strings,
   allowing the calling application to delegate the text decoding step
   to the CPython runtime.

   Added in version 3.8.

int Py_Main(int argc, wchar_t **argv)
    * Part of the Stable ABI.*

   The main program for the standard interpreter, encapsulating a full
   initialization/finalization cycle, as well as additional behaviour
   to implement reading configurations settings from the environment
   and command line, and then executing "__main__" in accordance with
   Línea de comando.

   This is made available for programs which wish to support the full
   CPython command line interface, rather than just embedding a Python
   runtime in a larger application.

   The *argc* and *argv* parameters are similar to those which are
   passed to a C program's "main()" function, except that the *argv*
   entries are first converted to "wchar_t" using "Py_DecodeLocale()".
   It is also important to note that the argument list entries may be
   modified to point to strings other than those passed in (however,
   the contents of the strings pointed to by the argument list are not
   modified).

   The return value is "2" if the argument list does not represent a
   valid Python command line, and otherwise the same as
   "Py_RunMain()".

   In terms of the CPython runtime configuration APIs documented in
   the runtime configuration section (and without accounting for error
   handling), "Py_Main" is approximately equivalent to:

      PyConfig config;
      PyConfig_InitPythonConfig(&config);
      PyConfig_SetArgv(&config, argc, argv);
      Py_InitializeFromConfig(&config);
      PyConfig_Clear(&config);

      Py_RunMain();

   In normal usage, an embedding application will call this function
   *instead* of calling "Py_Initialize()", "Py_InitializeEx()" or
   "Py_InitializeFromConfig()" directly, and all settings will be
   applied as described elsewhere in this documentation. If this
   function is instead called *after* a preceding runtime
   initialization API call, then exactly which environmental and
   command line configuration settings will be updated is version
   dependent (as it depends on which settings correctly support being
   modified after they have already been set once when the runtime was
   first initialized).

int Py_RunMain(void)

   Executes the main module in a fully configured CPython runtime.

   Executes the command ("PyConfig.run_command"), the script
   ("PyConfig.run_filename") or the module ("PyConfig.run_module")
   specified on the command line or in the configuration. If none of
   these values are set, runs the interactive Python prompt (REPL)
   using the "__main__" module's global namespace.

   If "PyConfig.inspect" is not set (the default), the return value
   will be "0" if the interpreter exits normally (that is, without
   raising an exception), the exit status of an unhandled
   "SystemExit", or "1" for any other unhandled exception.

   If "PyConfig.inspect" is set (such as when the "-i" option is
   used), rather than returning when the interpreter exits, execution
   will instead resume in an interactive Python prompt (REPL) using
   the "__main__" module's global namespace. If the interpreter exited
   with an exception, it is immediately raised in the REPL session.
   The function return value is then determined by the way the *REPL
   session* terminates: "0", "1", or the status of a "SystemExit", as
   specified above.

   This function always finalizes the Python interpreter before it
   returns.

   See Python Configuration for an example of a customized Python that
   always runs in isolated mode using "Py_RunMain()".

int PyUnstable_AtExit(PyInterpreterState *interp, void (*func)(void*), void *data)

   *This is Unstable API. It may change without warning in minor
   releases.*

   Register an "atexit" callback for the target interpreter *interp*.
   This is similar to "Py_AtExit()", but takes an explicit interpreter
   and data pointer for the callback.

   There must be an *attached thread state* for *interp*.

   Added in version 3.13.


Parámetros de todo el proceso
=============================

void Py_SetProgramName(const wchar_t *name)
    * Part of the Stable ABI.*

   Esta API se mantiene para la compatibilidad con versiones
   anteriores: en su lugar, se debe usar la configuración de
   "PyConfig.program_name", consulta Configuración de inicialización
   de Python.

   Esta función debería llamarse antes "Py_Initialize()" se llama por
   primera vez, si es que se llama. Le dice al intérprete el valor del
   argumento "argv[0]" para la función "main()" del programa
   (convertido a caracteres anchos). Esto es utilizado por
   "Py_GetPath()" y algunas otras funciones a continuación para
   encontrar las bibliotecas de tiempo de ejecución de Python
   relativas al ejecutable del intérprete. El valor predeterminado es
   "'python'". El argumento debe apuntar a una cadena de caracteres
   anchos terminada en cero en almacenamiento estático cuyo contenido
   no cambiará mientras dure la ejecución del programa. Ningún código
   en el intérprete de Python cambiará el contenido de este
   almacenamiento.

   Use "Py_DecodeLocale()" to decode a bytes string to get a wchar_t*
   string.

   Deprecated since version 3.11, will be removed in version 3.15.

wchar_t *Py_GetProgramName()
    * Part of the Stable ABI.*

   Devuelve el nombre del programa establecido con
   "PyConfig.program_name" o el valor predeterminado. La cadena
   devuelta apunta a un almacenamiento estático; el llamador no debe
   modificar su valor.

   Esta función ya no se puede llamar antes de "Py_Initialize()", de
   otra forma retornará "NULL".

   Distinto en la versión 3.10: Todas las siguientes funciones deben
   llamarse después de "Py_Initialize()", de lo contrario retornará
   "NULL".

   Deprecated since version 3.13, will be removed in version 3.15: Use
   "PyConfig_Get("executable")" ("sys.executable") instead.

wchar_t *Py_GetPrefix()
    * Part of the Stable ABI.*

   Return the *prefix* for installed platform-independent files. This
   is derived through a number of complicated rules from the program
   name set with "PyConfig.program_name" and some environment
   variables; for example, if the program name is
   "'/usr/local/bin/python'", the prefix is "'/usr/local'". The
   returned string points into static storage; the caller should not
   modify its value.  This corresponds to the **prefix** variable in
   the top-level "Makefile" and the "--prefix" argument to the
   **configure** script at build time.  The value is available to
   Python code as "sys.base_prefix". It is only useful on Unix.  See
   also the next function.

   Esta función ya no se puede llamar antes de "Py_Initialize()", de
   otra forma retornará "NULL".

   Distinto en la versión 3.10: Todas las siguientes funciones deben
   llamarse después de "Py_Initialize()", de lo contrario retornará
   "NULL".

   Deprecated since version 3.13, will be removed in version 3.15: Use
   "PyConfig_Get("base_prefix")" ("sys.base_prefix") instead. Use
   "PyConfig_Get("prefix")" ("sys.prefix") if virtual environments
   need to be handled.

wchar_t *Py_GetExecPrefix()
    * Part of the Stable ABI.*

   Return the *exec-prefix* for installed platform-*dependent* files.
   This is derived through a number of complicated rules from the
   program name set with "PyConfig.program_name" and some environment
   variables; for example, if the program name is
   "'/usr/local/bin/python'", the exec-prefix is "'/usr/local'".  The
   returned string points into static storage; the caller should not
   modify its value.  This corresponds to the **exec_prefix** variable
   in the top-level "Makefile" and the "--exec-prefix" argument to the
   **configure** script at build  time.  The value is available to
   Python code as "sys.base_exec_prefix".  It is only useful on Unix.

   Antecedentes: el prefijo *exec* difiere del prefijo cuando los
   archivos dependientes de la plataforma (como ejecutables y
   bibliotecas compartidas) se instalan en un árbol de directorios
   diferente. En una instalación típica, los archivos dependientes de
   la plataforma pueden instalarse en el subárbol "/usr/local/plat"
   mientras que la plataforma independiente puede instalarse en
   "/usr/local".

   En términos generales, una plataforma es una combinación de
   familias de hardware y software, por ejemplo, las máquinas Sparc
   que ejecutan el sistema operativo Solaris 2.x se consideran la
   misma plataforma, pero las máquinas Intel que ejecutan Solaris 2.x
   son otra plataforma, y las máquinas Intel que ejecutan Linux son
   otra plataforma más. Las diferentes revisiones importantes del
   mismo sistema operativo generalmente también forman plataformas
   diferentes. Los sistemas operativos que no son Unix son una
   historia diferente; Las estrategias de instalación en esos sistemas
   son tan diferentes que el prefijo y el prefijo "exec" no tienen
   sentido y se configuran en la cadena vacía. Tenga en cuenta que los
   archivos de bytecode compilados de Python son independientes de la
   plataforma (¡pero no independientes de la versión de Python con la
   que fueron compilados!).

   Los administradores de sistemas sabrán cómo configurar los
   programas **mount** o **automount** para compartir "/usr/local"
   entre plataformas mientras que "/usr/local/plat" sea un sistema de
   archivos diferente para cada plataforma.

   Esta función ya no se puede llamar antes de "Py_Initialize()", de
   otra forma retornará "NULL".

   Distinto en la versión 3.10: Todas las siguientes funciones deben
   llamarse después de "Py_Initialize()", de lo contrario retornará
   "NULL".

   Deprecated since version 3.13, will be removed in version 3.15: Use
   "PyConfig_Get("base_exec_prefix")" ("sys.base_exec_prefix")
   instead. Use "PyConfig_Get("exec_prefix")" ("sys.exec_prefix") if
   virtual environments need to be handled.

wchar_t *Py_GetProgramFullPath()
    * Part of the Stable ABI.*

   Devuelve el nombre completo del programa ejecutable de Python; esto
   se calcula como un efecto secundario de derivar la ruta de búsqueda
   del módulo predeterminado a partir del nombre del programa
   (establecido por "PyConfig.program_name"). La cadena devuelta
   apunta a un almacenamiento estático; el llamador no debe modificar
   su valor. El valor está disponible para el código Python como
   "sys.executable".

   Esta función ya no se puede llamar antes de "Py_Initialize()", de
   otra forma retornará "NULL".

   Distinto en la versión 3.10: Todas las siguientes funciones deben
   llamarse después de "Py_Initialize()", de lo contrario retornará
   "NULL".

   Deprecated since version 3.13, will be removed in version 3.15: Use
   "PyConfig_Get("executable")" ("sys.executable") instead.

wchar_t *Py_GetPath()
    * Part of the Stable ABI.*

   Devuelve la ruta de búsqueda del módulo predeterminada; esto se
   calcula a partir del nombre del programa (establecido por
   "PyConfig.program_name") y algunas variables de entorno. La cadena
   devuelta consta de una serie de nombres de directorio separados por
   un carácter delimitador dependiente de la plataforma. El carácter
   delimitador es "':'" en Unix y macOS, "';'" en Windows. La cadena
   devuelta apunta a un almacenamiento estático; el llamador no debe
   modificar su valor. La lista "sys.path" se inicializa con este
   valor al iniciar el intérprete; se puede modificar (y generalmente
   se modifica) más tarde para cambiar la ruta de búsqueda para cargar
   módulos.

   Esta función ya no se puede llamar antes de "Py_Initialize()", de
   otra forma retornará "NULL".

   Distinto en la versión 3.10: Todas las siguientes funciones deben
   llamarse después de "Py_Initialize()", de lo contrario retornará
   "NULL".

   Deprecated since version 3.13, will be removed in version 3.15: Use
   "PyConfig_Get("module_search_paths")" ("sys.path") instead.

const char *Py_GetVersion()
    * Part of the Stable ABI.*

   Retorna la versión de este intérprete de Python. Esta es una cadena
   de caracteres que se parece a

      "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"

   La primera palabra (hasta el primer carácter de espacio) es la
   versión actual de Python; los primeros tres caracteres son la
   versión mayor y menor separados por un punto. La cadena de
   caracteres retornada apunta al almacenamiento estático; la persona
   que llama no debe modificar su valor. El valor está disponible para
   el código Python como "sys.version".

   Consulta también la constante "Py_Version".

const char *Py_GetPlatform()
    * Part of the Stable ABI.*

   Retorna el identificador de plataforma para la plataforma actual.
   En Unix, esto se forma a partir del nombre "oficial" del sistema
   operativo, convertido a minúsculas, seguido del número de revisión
   principal; por ejemplo, para Solaris 2.x, que también se conoce
   como SunOS 5.x, el valor es "'sunos5'". En macOS, es "'darwin'". En
   Windows, es "'win'". La cadena de caracteres retornada apunta al
   almacenamiento estático; la persona que llama no debe modificar su
   valor. El valor está disponible para el código de Python como
   "sys.platform".

const char *Py_GetCopyright()
    * Part of the Stable ABI.*

   Retorna la cadena de caracteres de copyright oficial para la
   versión actual de Python, por ejemplo

   "'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'"

   La cadena de caracteres retornada apunta al almacenamiento
   estático; la persona que llama no debe modificar su valor. El valor
   está disponible para el código de Python como "sys.copyright".

const char *Py_GetCompiler()
    * Part of the Stable ABI.*

   Retorna una indicación del compilador utilizado para construir la
   versión actual de Python, entre corchetes, por ejemplo:

      "[GCC 2.7.2.2]"

   La cadena de caracteres retornada apunta al almacenamiento
   estático; la persona que llama no debe modificar su valor. El valor
   está disponible para el código Python como parte de la variable
   "sys.version".

const char *Py_GetBuildInfo()
    * Part of the Stable ABI.*

   Retorna información sobre el número de secuencia y la fecha y hora
   de compilación de la instancia actual de intérprete de Python, por
   ejemplo:

      "#67, Aug  1 1997, 22:34:28"

   La cadena de caracteres retornada apunta al almacenamiento
   estático; la persona que llama no debe modificar su valor. El valor
   está disponible para el código Python como parte de la variable
   "sys.version".

void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
    * Part of the Stable ABI.*

   Esta API se mantiene para la compatibilidad con versiones
   anteriores: en su lugar, se debe usar la configuración de
   "PyConfig.argv", "PyConfig.parse_argv" y "PyConfig.safe_path",
   consulta Configuración de inicialización de Python.

   Establece "sys.argv" basado en *argc* y *argv*. Estos parámetros
   son similares a los pasados a la función del programa "main()" con
   la diferencia de que la primera entrada debe referirse al archivo
   de la secuencia de comandos (*script*) que se ejecutará en lugar
   del ejecutable que aloja el intérprete de Python. Si no se ejecuta
   una secuencia de comandos (*script*), la primera entrada en *argv*
   puede ser una cadena de caracteres vacía. Si esta función no puede
   inicializar "sys.argv", una condición fatal se señala usando
   "Py_FatalError()".

   Si *updatepath* es cero, esto es todo lo que hace la función. Si
   *updatepath* no es cero, la función también modifica "sys.path" de
   acuerdo con el siguiente algoritmo:

   * Si el nombre de una secuencia de comandos (*script*) existente se
     pasa en "argv[0]", la ruta absoluta del directorio donde se
     encuentra el *script* se antepone a "sys.path".

   * De lo contrario (es decir, si *argc* es "0" o "argv[0]" no apunta
     a un nombre de archivo existente), una cadena de caracteres vacía
     se antepone a "sys.path", que es lo mismo que anteponer el
     directorio de trabajo actual (""."").

   Use "Py_DecodeLocale()" to decode a bytes string to get a wchar_t*
   string.

   Consulta también los miembros de "PyConfig.orig_argv" y
   "PyConfig.argv" de Python Initialization Configuration.

   Nota:

     Se recomienda que las aplicaciones que incorporan el intérprete
     de Python para fines distintos a la ejecución de un único script
     pasen "0" como *updatepath* y actualicen "sys.path" por sí mismas
     si así lo desean. Consulte **CVE 2008-5983**.En las versiones
     anteriores a 3.1.3, puede lograr el mismo efecto quitando
     manualmente el primer elemento (*popping*) "sys.path" después de
     haber llamado "PySys_SetArgv()", por ejemplo usando

        PyRun_SimpleString("import sys; sys.path.pop(0)\n");

   Added in version 3.1.3.

   Deprecated since version 3.11, will be removed in version 3.15.

void PySys_SetArgv(int argc, wchar_t **argv)
    * Part of the Stable ABI.*

   Esta API se mantiene para la compatibilidad con versiones
   anteriores: en su lugar, se debe usar la configuración de
   "PyConfig.argv" y "PyConfig.parse_argv", consulta Configuración de
   inicialización de Python.

   Esta función funciona como "PySys_SetArgvEx()" con *updatepath*
   establecido en "1" a menos que el intérprete **python** se haya
   iniciado con la opción "-I".

   Use "Py_DecodeLocale()" to decode a bytes string to get a wchar_t*
   string.

   Consulta también los miembros de "PyConfig.orig_argv" y
   "PyConfig.argv" de Python Initialization Configuration.

   Distinto en la versión 3.4: El valor *updatepath* depende de la
   opción "-I".

   Deprecated since version 3.11, will be removed in version 3.15.

void Py_SetPythonHome(const wchar_t *home)
    * Part of the Stable ABI.*

   Esta API se mantiene para la compatibilidad con versiones
   anteriores: en su lugar, se debe usar la configuración de
   "PyConfig.home", consulta Configuración de inicialización de
   Python.

   Establece el directorio "inicio" (*"home"*) predeterminado, es
   decir, la ubicación de las bibliotecas estándar de Python. Ver
   "PYTHONHOME" para el significado de la cadena de caracteres de
   argumento.

   El argumento debe apuntar a una cadena de caracteres terminada en
   cero en el almacenamiento estático cuyo contenido no cambiará
   mientras dure la ejecución del programa. Ningún código en el
   intérprete de Python cambiará el contenido de este almacenamiento.

   Use "Py_DecodeLocale()" to decode a bytes string to get a wchar_t*
   string.

   Deprecated since version 3.11, will be removed in version 3.15.

wchar_t *Py_GetPythonHome()
    * Part of the Stable ABI.*

   Devuelve el "inicio" predeterminado, es decir, el valor establecido
   por "PyConfig.home", o el valor de la variable de entorno
   "PYTHONHOME" si está establecida.

   Esta función ya no se puede llamar antes de "Py_Initialize()", de
   otra forma retornará "NULL".

   Distinto en la versión 3.10: Todas las siguientes funciones deben
   llamarse después de "Py_Initialize()", de lo contrario retornará
   "NULL".

   Deprecated since version 3.13, will be removed in version 3.15: Use
   "PyConfig_Get("home")" or the "PYTHONHOME" environment variable
   instead.


Estado del hilo y el bloqueo global del intérprete
==================================================

Unless on a *free-threaded* build of *CPython*, the Python interpreter
is not fully thread-safe.  In order to support multi-threaded Python
programs, there's a global lock, called the *global interpreter lock*
or *GIL*, that must be held by the current thread before it can safely
access Python objects. Without the lock, even the simplest operations
could cause problems in a multi-threaded program: for example, when
two threads simultaneously increment the reference count of the same
object, the reference count could end up being incremented only once
instead of twice.

Por lo tanto, existe la regla de que solo el hilo que ha adquirido
*GIL* puede operar en objetos Python o llamar a funciones API
Python/C. Para emular la concurrencia de ejecución, el intérprete
regularmente intenta cambiar los hilos (ver
"sys.setswitchinterval()"). El bloqueo también se libera para bloquear
potencialmente las operaciones de E/S, como leer o escribir un
archivo, para que otros hilos de Python puedan ejecutarse mientras
tanto.

The Python interpreter keeps some thread-specific bookkeeping
information inside a data structure called "PyThreadState", known as a
*thread state*. Each OS thread has a thread-local pointer to a
"PyThreadState"; a thread state referenced by this pointer is
considered to be *attached*.

A thread can only have one *attached thread state* at a time. An
attached thread state is typically analogous with holding the *GIL*,
except on *free-threaded* builds.  On builds with the *GIL* enabled,
*attaching* a thread state will block until the *GIL* can be acquired.
However,  even on builds with the *GIL* disabled, it is still required
to have an attached thread state to call most of the C API.

In general, there will always be an *attached thread state* when using
Python's C API. Only in some specific cases (such as in a
"Py_BEGIN_ALLOW_THREADS" block) will the thread not have an attached
thread state. If uncertain, check if "PyThreadState_GetUnchecked()"
returns "NULL".


Detaching the thread state from extension code
----------------------------------------------

Most extension code manipulating the *thread state* has the following
simple structure:

   Save the thread state in a local variable.
   ... Do some blocking I/O operation ...
   Restore the thread state from the local variable.

Esto es tan común que existen un par de macros para simplificarlo:

   Py_BEGIN_ALLOW_THREADS
   ... Hace alguna operación bloqueante en I/O ...
   Py_END_ALLOW_THREADS

La macro "Py_BEGIN_ALLOW_THREADS" abre un nuevo bloque y declara una
variable local oculta; la macro "Py_END_ALLOW_THREADS" cierra el
bloque.

El bloque anterior se expande al siguiente código:

   PyThreadState *_save;

   _save = PyEval_SaveThread();
   ... Realizar alguna operación de bloqueo de E/S...
   PyEval_RestoreThread(_save);

Here is how these functions work:

The *attached thread state* holds the *GIL* for the entire
interpreter. When detaching the *attached thread state*, the *GIL* is
released, allowing other threads to attach a thread state to their own
thread, thus getting the *GIL* and can start executing. The pointer to
the prior *attached thread state* is stored as a local variable. Upon
reaching "Py_END_ALLOW_THREADS", the thread state that was previously
*attached* is passed to "PyEval_RestoreThread()". This function will
block until another releases its *thread state*, thus allowing the old
*thread state* to get re-attached and the C API can be called again.

For *free-threaded* builds, the *GIL* is normally out of the question,
but detaching the *thread state* is still required for blocking I/O
and long operations. The difference is that threads don't have to wait
for the *GIL* to be released to attach their thread state, allowing
true multi-core parallelism.

Nota:

  Calling system I/O functions is the most common use case for
  detaching the *thread state*, but it can also be useful before
  calling long-running computations which don't need access to Python
  objects, such as compression or cryptographic functions operating
  over memory buffers. For example, the standard "zlib" and "hashlib"
  modules detach the *thread state* when compressing or hashing data.


Hilos creados sin Python
------------------------

When threads are created using the dedicated Python APIs (such as the
"threading" module), a thread state is automatically associated to
them and the code showed above is therefore correct.  However, when
threads are created from C (for example by a third-party library with
its own thread management), they don't hold the *GIL*, because they
don't have an *attached thread state*.

If you need to call Python code from these threads (often this will be
part of a callback API provided by the aforementioned third-party
library), you must first register these threads with the interpreter
by creating an *attached thread state* before you can start using the
Python/C API.  When you are done, you should detach the *thread
state*, and finally free it.

Las funciones "PyGILState_Ensure()" y "PyGILState_Release()" hacen
todo lo anterior automáticamente. El idioma típico para llamar a
Python desde un hilo C es:

   PyGILState_STATE gstate;
   gstate = PyGILState_Ensure();

   /* Realizar acciones de Python aquí. */
   result = CallSomeFunction();
   /* evaluar el resultado o manejar la excepción */

   /* Liberar el hilo. No se permite ninguna API de Python más allá de este punto. */
   PyGILState_Release(gstate);

Note that the "PyGILState_*" functions assume there is only one global
interpreter (created automatically by "Py_Initialize()").  Python
supports the creation of additional interpreters (using
"Py_NewInterpreter()"), but mixing multiple interpreters and the
"PyGILState_*" API is unsupported. This is because
"PyGILState_Ensure()" and similar functions default to *attaching* a
*thread state* for the main interpreter, meaning that the thread can't
safely interact with the calling subinterpreter.


Supporting subinterpreters in non-Python threads
------------------------------------------------

If you would like to support subinterpreters with non-Python created
threads, you must use the "PyThreadState_*" API instead of the
traditional "PyGILState_*" API.

In particular, you must store the interpreter state from the calling
function and pass it to "PyThreadState_New()", which will ensure that
the *thread state* is targeting the correct interpreter:

   /* The return value of PyInterpreterState_Get() from the
      function that created this thread. */
   PyInterpreterState *interp = ThreadData->interp;
   PyThreadState *tstate = PyThreadState_New(interp);
   PyThreadState_Swap(tstate);

   /* GIL of the subinterpreter is now held.
      Perform Python actions here. */
   result = CallSomeFunction();
   /* evaluate result or handle exception */

   /* Destroy the thread state. No Python API allowed beyond this point. */
   PyThreadState_Clear(tstate);
   PyThreadState_DeleteCurrent();


Precauciones sobre "fork()"
---------------------------

Otra cosa importante a tener en cuenta sobre los hilos es su
comportamiento frente a la llamada C "fork()". En la mayoría de los
sistemas con "fork()", después de que un proceso se bifurca, solo
existirá el hilo que emitió el *fork*. Esto tiene un impacto concreto
tanto en cómo se deben manejar las cerraduras como en todo el estado
almacenado en el tiempo de ejecución de CPython.

El hecho de que solo permanezca el hilo "actual" significa que los
bloqueos mantenidos por otros hilos nunca se liberarán. Python
resuelve esto para "os.fork()" adquiriendo los bloqueos que usa
internamente antes de la bifurcación y liberándolos después. Además,
restablece cualquier Lock objects en el hijo. Al extender o incrustar
Python, no hay forma de informar a Python de bloqueos adicionales (que
no sean de Python) que deben adquirirse antes o restablecerse después
de una bifurcación. Se necesitarían usar recursos del sistema
operativo como "pthread_atfork()" para lograr lo mismo. Además, al
extender o incrustar Python, llamar a "fork()" directamente en lugar
de a través de "os.fork()" (y regresar a Python o llamar a Python)
puede resultar en un bloqueo por uno de los bloqueos internos de
Python que está retenido por un hilo que está inactivo después de la
bifurcación. "PyOS_AfterFork_Child()" intenta restablecer los bloqueos
necesarios, pero no siempre puede hacerlo.

El hecho de que todos los otros hilos desaparezcan también significa
que el estado de ejecución de CPython debe limpiarse correctamente, lo
que "os.fork()" lo hace. Esto significa finalizar todos los demás
objetos "PyThreadState" que pertenecen al intérprete actual y todos
los demás objetos "PyInterpreterState". Debido a esto y a la
naturaleza especial del intérprete "principal", "fork()" solo debería
llamarse en el hilo "principal" de ese intérprete, donde el CPython
global el tiempo de ejecución se inicializó originalmente. La única
excepción es si "exec()" se llamará inmediatamente después.


Cautions regarding runtime finalization
---------------------------------------

In the late stage of *interpreter shutdown*, after attempting to wait
for non-daemon threads to exit (though this can be interrupted by
"KeyboardInterrupt") and running the "atexit" functions, the runtime
is marked as *finalizing*: "Py_IsFinalizing()" and
"sys.is_finalizing()" return true.  At this point, only the
*finalization thread* that initiated finalization (typically the main
thread) is allowed to acquire the *GIL*.

If any thread, other than the finalization thread, attempts to attach
a *thread state* during finalization, either explicitly or implicitly,
the thread enters **a permanently blocked state** where it remains
until the program exits.  In most cases this is harmless, but this can
result in deadlock if a later stage of finalization attempts to
acquire a lock owned by the blocked thread, or otherwise waits on the
blocked thread.

Gross? Yes. This prevents random crashes and/or unexpectedly skipped
C++ finalizations further up the call stack when such threads were
forcibly exited here in CPython 3.13 and earlier. The CPython runtime
*thread state* C APIs have never had any error reporting or handling
expectations at *thread state* attachment time that would've allowed
for graceful exit from this situation. Changing that would require new
stable C APIs and rewriting the majority of C code in the CPython
ecosystem to use those with error handling.


API de alto nivel
-----------------

Estos son los tipos y funciones más utilizados al escribir código de
extensión C o al incrustar el intérprete de Python:

type PyInterpreterState
    * Part of the Limited API (as an opaque struct).*

   Esta estructura de datos representa el estado compartido por varios
   subprocesos cooperantes. Los hilos que pertenecen al mismo
   intérprete comparten la administración de su módulo y algunos otros
   elementos internos. No hay miembros públicos en esta estructura.

   Los hilos que pertenecen a diferentes intérpretes inicialmente no
   comparten nada, excepto el estado del proceso como memoria
   disponible, descriptores de archivos abiertos y demás. El bloqueo
   global del intérprete también es compartido por todos los hilos,
   independientemente de a qué intérprete pertenezcan.

   Distinto en la versión 3.12: **PEP 684** introduced the possibility
   of a per-interpreter GIL. See "Py_NewInterpreterFromConfig()".

type PyThreadState
    * Part of the Limited API (as an opaque struct).*

   Esta estructura de datos representa el estado de un único
   subproceso. El único miembro de datos público es:

   PyInterpreterState *interp

      Estado del intérprete de este hilo.

void PyEval_InitThreads()
    * Part of the Stable ABI.*

   Función deprecada que no hace nada.

   En Python 3.6 y versiones anteriores, esta función creaba el GIL si
   no existía.

   Distinto en la versión 3.9: La función ahora no hace nada.

   Distinto en la versión 3.7: Esta función ahora es llamada por
   "Py_Initialize()", por lo que ya no tiene que llamarla usted mismo.

   Distinto en la versión 3.2: Esta función ya no se puede llamar
   antes de "Py_Initialize()".

   Obsoleto desde la versión 3.9.

PyThreadState *PyEval_SaveThread()
    * Part of the Stable ABI.*

   Detach the *attached thread state* and return it. The thread will
   have no *thread state* upon returning.

void PyEval_RestoreThread(PyThreadState *tstate)
    * Part of the Stable ABI.*

   Set the *attached thread state* to *tstate*. The passed *thread
   state* **should not** be *attached*, otherwise deadlock ensues.
   *tstate* will be attached upon returning.

   Nota:

     Calling this function from a thread when the runtime is
     finalizing will hang the thread until the program exits, even if
     the thread was not created by Python.  Refer to Cautions
     regarding runtime finalization for more details.

   Distinto en la versión 3.14: Hangs the current thread, rather than
   terminating it, if called while the interpreter is finalizing.

PyThreadState *PyThreadState_Get()
    * Part of the Stable ABI.*

   Return the *attached thread state*. If the thread has no attached
   thread state, (such as when inside of "Py_BEGIN_ALLOW_THREADS"
   block), then this issues a fatal error (so that the caller needn't
   check for "NULL").

   Véase también "PyThreadState_GetUnchecked()".

PyThreadState *PyThreadState_GetUnchecked()

   Similar a "PyThreadState_Get()", pero no mata el proceso con un
   error fatal si es NULL. El llamador es responsable de verificar si
   el resultado es NULL.

   Added in version 3.13: En Python 3.5 a 3.12, la función era privada
   y se conocía como "_PyThreadState_UncheckedGet()".

PyThreadState *PyThreadState_Swap(PyThreadState *tstate)
    * Part of the Stable ABI.*

   Set the *attached thread state* to *tstate*, and return the *thread
   state* that was attached prior to calling.

   This function is safe to call without an *attached thread state*;
   it will simply return "NULL" indicating that there was no prior
   thread state.

   Ver también: "PyEval_ReleaseThread()"

   Nota:

     Similar to "PyGILState_Ensure()", this function will hang the
     thread if the runtime is finalizing.

Las siguientes funciones utilizan almacenamiento local de hilos y no
son compatibles con subinterpretes:

type PyGILState_STATE
    * Part of the Stable ABI.*

   The type of the value returned by "PyGILState_Ensure()" and passed
   to "PyGILState_Release()".

   enumerator PyGILState_LOCKED

      The GIL was already held when "PyGILState_Ensure()" was called.

   enumerator PyGILState_UNLOCKED

      The GIL was not held when "PyGILState_Ensure()" was called.

PyGILState_STATE PyGILState_Ensure()
    * Part of the Stable ABI.*

   Ensure that the current thread is ready to call the Python C API
   regardless of the current state of Python, or of the *attached
   thread state*. This may be called as many times as desired by a
   thread as long as each call is matched with a call to
   "PyGILState_Release()". In general, other thread-related APIs may
   be used between "PyGILState_Ensure()" and "PyGILState_Release()"
   calls as long as the thread state is restored to its previous state
   before the Release().  For example, normal usage of the
   "Py_BEGIN_ALLOW_THREADS" and "Py_END_ALLOW_THREADS" macros is
   acceptable.

   The return value is an opaque "handle" to the *attached thread
   state* when "PyGILState_Ensure()" was called, and must be passed to
   "PyGILState_Release()" to ensure Python is left in the same state.
   Even though recursive calls are allowed, these handles *cannot* be
   shared - each unique call to "PyGILState_Ensure()" must save the
   handle for its call to "PyGILState_Release()".

   When the function returns, there will be an *attached thread state*
   and the thread will be able to call arbitrary Python code.  Failure
   is a fatal error.

   Advertencia:

     Calling this function when the runtime is finalizing is unsafe.
     Doing so will either hang the thread until the program ends, or
     fully crash the interpreter in rare cases. Refer to Cautions
     regarding runtime finalization for more details.

   Distinto en la versión 3.14: Hangs the current thread, rather than
   terminating it, if called while the interpreter is finalizing.

void PyGILState_Release(PyGILState_STATE)
    * Part of the Stable ABI.*

   Libera cualquier recurso previamente adquirido. Después de esta
   llamada, el estado de Python será el mismo que antes de la llamada
   correspondiente "PyGILState_Ensure()" (pero en general este estado
   será desconocido para la persona que llama, de ahí el uso de la API
   "GILState").

   Cada llamada a "PyGILState_Ensure()" debe coincidir con una llamada
   a "PyGILState_Release()" en el mismo hilo.

PyThreadState *PyGILState_GetThisThreadState()
    * Part of the Stable ABI.*

   Get the *attached thread state* for this thread.  May return "NULL"
   if no GILState API has been used on the current thread.  Note that
   the main thread always has such a thread-state, even if no auto-
   thread-state call has been made on the main thread.  This is mainly
   a helper/diagnostic function.

   Nota:

     This function may return non-"NULL" even when the *thread state*
     is detached. Prefer "PyThreadState_Get()" or
     "PyThreadState_GetUnchecked()" for most cases.

   Ver también: "PyThreadState_Get()"

int PyGILState_Check()

   Return "1" if the current thread is holding the *GIL* and "0"
   otherwise. This function can be called from any thread at any time.
   Only if it has had its *thread state* initialized via
   "PyGILState_Ensure()" will it return "1". This is mainly a
   helper/diagnostic function.  It can be useful for example in
   callback contexts or memory allocation functions when knowing that
   the *GIL* is locked can allow the caller to perform sensitive
   actions or otherwise behave differently.

   Nota:

     If the current Python process has ever created a subinterpreter,
     this function will *always* return "1". Prefer
     "PyThreadState_GetUnchecked()" for most cases.

   Added in version 3.4.

Las siguientes macros se usan normalmente sin punto y coma final;
busque, por ejemplo, el uso en la distribución fuente de Python.

Py_BEGIN_ALLOW_THREADS
    * Part of the Stable ABI.*

   Esta macro se expande a "{PyThreadState *_save; _save =
   PyEval_SaveThread();". Tenga en cuenta que contiene una llave de
   apertura; debe coincidir con la siguiente macro
   "Py_END_ALLOW_THREADS". Ver arriba para una discusión más detallada
   de esta macro.

Py_END_ALLOW_THREADS
    * Part of the Stable ABI.*

   Esta macro se expande a "PyEval_RestoreThread(_save); }". Tenga en
   cuenta que contiene una llave de cierre; debe coincidir con una
   macro anterior "Py_BEGIN_ALLOW_THREADS". Ver arriba para una
   discusión más detallada de esta macro.

Py_BLOCK_THREADS
    * Part of the Stable ABI.*

   Esta macro se expande a "PyEval_RestoreThread(_save);": es
   equivalente a "Py_END_ALLOW_THREADS" sin la llave de cierre.

Py_UNBLOCK_THREADS
    * Part of the Stable ABI.*

   Esta macro se expande a "_save = PyEval_SaveThread();": es
   equivalente a "Py_BEGIN_ALLOW_THREADS" sin la llave de apertura y
   la declaración de variable.


API de bajo nivel
-----------------

Todas las siguientes funciones deben llamarse después de
"Py_Initialize()".

Distinto en la versión 3.7: "Py_Initialize()" now initializes the
*GIL* and sets an *attached thread state*.

PyInterpreterState *PyInterpreterState_New()
    * Part of the Stable ABI.*

   Create a new interpreter state object.  An *attached thread state*
   is not needed, but may optionally exist if it is necessary to
   serialize calls to this function.

   Genera un evento de auditoría "python.PyInterpreterState_New" sin
   argumentos.

void PyInterpreterState_Clear(PyInterpreterState *interp)
    * Part of the Stable ABI.*

   Reset all information in an interpreter state object.  There must
   be an *attached thread state* for the interpreter.

   Lanza una eventos de auditoría "python.PyInterpreterState Clear"
   sin argumentos.

void PyInterpreterState_Delete(PyInterpreterState *interp)
    * Part of the Stable ABI.*

   Destroy an interpreter state object.  There **should not** be an
   *attached thread state* for the target interpreter. The interpreter
   state must have been reset with a previous call to
   "PyInterpreterState_Clear()".

PyThreadState *PyThreadState_New(PyInterpreterState *interp)
    * Part of the Stable ABI.*

   Create a new thread state object belonging to the given interpreter
   object. An *attached thread state* is not needed.

void PyThreadState_Clear(PyThreadState *tstate)
    * Part of the Stable ABI.*

   Reset all information in a *thread state* object.  *tstate* must be
   *attached*

   Distinto en la versión 3.9: This function now calls the
   "PyThreadState.on_delete" callback. Previously, that happened in
   "PyThreadState_Delete()".

   Distinto en la versión 3.13: The "PyThreadState.on_delete" callback
   was removed.

void PyThreadState_Delete(PyThreadState *tstate)
    * Part of the Stable ABI.*

   Destroy a *thread state* object.  *tstate* should not be *attached*
   to any thread. *tstate* must have been reset with a previous call
   to "PyThreadState_Clear()".

void PyThreadState_DeleteCurrent(void)

   Detach the *attached thread state* (which must have been reset with
   a previous call to "PyThreadState_Clear()") and then destroy it.

   No *thread state* will be *attached* upon returning.

PyFrameObject *PyThreadState_GetFrame(PyThreadState *tstate)
    * Part of the Stable ABI since version 3.10.*

   Obtiene el marco actual del estado del hilo de Python *tstate*.

   Retorna una *strong reference* (referencia sólida). Retorna "NULL"
   si no se está ejecutando ningún cuadro.

   Vea también "PyEval_GetFrame()".

   *tstate* must not be "NULL", and must be *attached*.

   Added in version 3.9.

uint64_t PyThreadState_GetID(PyThreadState *tstate)
    * Part of the Stable ABI since version 3.10.*

   Get the unique *thread state* identifier of the Python thread state
   *tstate*.

   *tstate* must not be "NULL", and must be *attached*.

   Added in version 3.9.

PyInterpreterState *PyThreadState_GetInterpreter(PyThreadState *tstate)
    * Part of the Stable ABI since version 3.10.*

   Obtiene el intérprete del estado del hilo de Python *tstate*.

   *tstate* must not be "NULL", and must be *attached*.

   Added in version 3.9.

void PyThreadState_EnterTracing(PyThreadState *tstate)

   Suspender el seguimiento y el perfilado en el estado del hilo de
   Python *tstate*.

   Reanudelos usando la función "PyThreadState_LeaveTracing()".

   Added in version 3.11.

void PyThreadState_LeaveTracing(PyThreadState *tstate)

   Reanudar el seguimiento y el perfilado en el estado del hilo de
   Python *tstate* suspendido por la función
   "PyThreadState_EnterTracing()".

   Consulte también las funciones "PyEval_SetTrace()" y
   "PyEval_SetProfile()".

   Added in version 3.11.

int PyUnstable_ThreadState_SetStackProtection(PyThreadState *tstate, void *stack_start_addr, size_t stack_size)

   *This is Unstable API. It may change without warning in minor
   releases.*

   Set the stack protection start address and stack protection size of
   a Python thread state.

   On success, return "0". On failure, set an exception and return
   "-1".

   CPython implements recursion control for C code by raising
   "RecursionError" when it notices that the machine execution stack
   is close to overflow. See for example the "Py_EnterRecursiveCall()"
   function. For this, it needs to know the location of the current
   thread's stack, which it normally gets from the operating system.
   When the stack is changed, for example using context switching
   techniques like the Boost library's "boost::context", you must call
   "PyUnstable_ThreadState_SetStackProtection()" to inform CPython of
   the change.

   Call "PyUnstable_ThreadState_SetStackProtection()" either before or
   after changing the stack. Do not call any other Python C API
   between the call and the stack change.

   See "PyUnstable_ThreadState_ResetStackProtection()" for undoing
   this operation.

   Added in version 3.14.1:

   Advertencia:

     This function was added in a bugfix release, and extensions that
     use it will be incompatible with Python 3.14.0. Most packaging
     tools for Python are not able to handle this incompatibility
     automatically, and will need explicit configuration. When using
     PyPA standards (wheels and source distributions), specify
     "Requires-Python: != 3.14.0.*" in core metadata.

void PyUnstable_ThreadState_ResetStackProtection(PyThreadState *tstate)

   *This is Unstable API. It may change without warning in minor
   releases.*

   Reset the stack protection start address and stack protection size
   of a Python thread state to the operating system defaults.

   See "PyUnstable_ThreadState_SetStackProtection()" for an
   explanation.

   Added in version 3.14.1:

   Advertencia:

     This function was added in a bugfix release, and extensions that
     use it will be incompatible with Python 3.14.0. Most packaging
     tools for Python are not able to handle this incompatibility
     automatically, and will need explicit configuration. When using
     PyPA standards (wheels and source distributions), specify
     "Requires-Python: != 3.14.0.*" in core metadata.

PyInterpreterState *PyInterpreterState_Get(void)
    * Part of the Stable ABI since version 3.9.*

   Obtiene el intérprete actual.

   Issue a fatal error if there no *attached thread state*. It cannot
   return NULL.

   Added in version 3.9.

int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
    * Part of the Stable ABI since version 3.7.*

   Retorna la identificación única del intérprete. Si hubo algún error
   al hacerlo, entonces se retorna "-1" y se establece un error.

   The caller must have an *attached thread state*.

   Added in version 3.7.

PyObject *PyInterpreterState_GetDict(PyInterpreterState *interp)
    *Return value: Borrowed reference.** Part of the Stable ABI since
   version 3.8.*

   Retorna un diccionario en el que se pueden almacenar datos
   específicos del intérprete. Si esta función retorna "NULL", no se
   ha producido ninguna excepción y la persona que llama debe suponer
   que no hay disponible una instrucción específica del intérprete.

   Esto no reemplaza a "PyModule_GetState()", que las extensiones
   deben usar para almacenar información de estado específica del
   intérprete.

   The returned dictionary is borrowed from the interpreter and is
   valid until interpreter shutdown.

   Added in version 3.8.

typedef PyObject *(*_PyFrameEvalFunction)(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)

   Tipo de función de evaluación de marcos.

   El parámetro *throwflag* es usado por el método de generadores
   "throw()": si no es cero, maneja la excepción actual.

   Distinto en la versión 3.9: La función ahora recibe un parámetro
   *tstate*.

   Distinto en la versión 3.11: El parámetro *frame* cambió de
   "PyFrameObject*" a "_PyInterpreterFrame*".

_PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)

   Obtiene la función de evaluación de marcos.

   Consulte **PEP 523** "Adición de una API de evaluación de marcos a
   CPython".

   Added in version 3.9.

void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)

   Configura la función de evaluación del marco.

   Consulte **PEP 523** "Adición de una API de evaluación de marcos a
   CPython".

   Added in version 3.9.

PyObject *PyThreadState_GetDict()
    *Return value: Borrowed reference.** Part of the Stable ABI.*

   Return a dictionary in which extensions can store thread-specific
   state information.  Each extension should use a unique key to use
   to store state in the dictionary.  It is okay to call this function
   when no *thread state* is *attached*. If this function returns
   "NULL", no exception has been raised and the caller should assume
   no thread state is attached.

int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
    * Part of the Stable ABI.*

   Asynchronously raise an exception in a thread. The *id* argument is
   the thread id of the target thread; *exc* is the exception object
   to be raised. This function does not steal any references to *exc*.
   To prevent naive misuse, you must write your own C extension to
   call this.  Must be called with an *attached thread state*. Returns
   the number of thread states modified; this is normally one, but
   will be zero if the thread id isn't found.  If *exc* is "NULL", the
   pending exception (if any) for the thread is cleared. This raises
   no exceptions.

   Distinto en la versión 3.7: El tipo del parámetro *id* cambia de
   long a unsigned long.

void PyEval_AcquireThread(PyThreadState *tstate)
    * Part of the Stable ABI.*

   *Attach* *tstate* to the current thread, which must not be "NULL"
   or already *attached*.

   The calling thread must not already have an *attached thread
   state*.

   Nota:

     Calling this function from a thread when the runtime is
     finalizing will hang the thread until the program exits, even if
     the thread was not created by Python.  Refer to Cautions
     regarding runtime finalization for more details.

   Distinto en la versión 3.8: Actualiza para ser coherente con
   "PyEval_RestoreThread()", "Py_END_ALLOW_THREADS()", y
   "PyGILState_Ensure()", y termina el hilo actual si se llama
   mientras el intérprete está finalizando.

   Distinto en la versión 3.14: Hangs the current thread, rather than
   terminating it, if called while the interpreter is finalizing.

   "PyEval_RestoreThread()" es una función de nivel superior que
   siempre está disponible (incluso cuando los subprocesos no se han
   inicializado).

void PyEval_ReleaseThread(PyThreadState *tstate)
    * Part of the Stable ABI.*

   Detach the *attached thread state*. The *tstate* argument, which
   must not be "NULL", is only used to check that it represents the
   *attached thread state* --- if it isn't, a fatal error is reported.

   "PyEval_SaveThread()" es una función de nivel superior que siempre
   está disponible (incluso cuando los hilos no se han inicializado).


Soporte de subinterprete
========================

Si bien en la mayoría de los usos, solo incrustará un solo intérprete
de Python, hay casos en los que necesita crear varios intérpretes
independientes en el mismo proceso y tal vez incluso en el mismo hilo.
Los subinterpretes le permiten hacer eso.

El intérprete "principal" es el primero creado cuando se inicializa el
tiempo de ejecución. Suele ser el único intérprete de Python en un
proceso. A diferencia de los subinterpretes, el intérprete principal
tiene responsabilidades globales de proceso únicas, como el manejo de
señales. También es responsable de la ejecución durante la
inicialización del tiempo de ejecución y generalmente es el intérprete
activo durante la finalización del tiempo de ejecución. La función
"PyInterpreterState_Main()" retorna un puntero a su estado.

Puede cambiar entre subinterpretes utilizando la función
"PyThreadState_Swap()". Puede crearlos y destruirlos utilizando las
siguientes funciones:

type PyInterpreterConfig

   Estructura que contiene la mayoría de los parámetros para
   configurar un subintérprete. Sus valores se utilizan únicamente en
   "Py_NewInterpreterFromConfig()" y nunca son modificados por el
   entorno de ejecución.

   Added in version 3.12.

   Campos de estructura:

   int use_main_obmalloc

      Si se trata de "0", el subintérprete utilizará su propio estado
      de asignador de "objetos". De lo contrario, utilizará
      (compartirá) el del intérprete principal.

      Si es "0", entonces "check_multi_interp_extensions" debe ser "1"
      (distinto de cero). Si es "1", entonces "gil" no debe ser
      "PyInterpreterConfig_OWN_GIL".

   int allow_fork

      Si es "0", el entorno de ejecución no admitirá la bifurcación
      del proceso en ningún subproceso en el que el subintérprete esté
      activo en ese momento. De lo contrario, la bifurcación no tendrá
      restricciones.

      Tenga en cuenta que el módulo "subprocess" aún funciona cuando
      no se permite la bifurcación.

   int allow_exec

      Si se trata de "0", el entorno de ejecución no admitirá la
      sustitución del proceso actual mediante exec (por ejemplo,
      "os.execv()") en ningún subproceso en el que el subintérprete
      esté activo en ese momento. De lo contrario, exec no tendrá
      restricciones.

      Tenga en cuenta que el módulo "subprocess" aún funciona cuando
      la ejecución no está permitida.

   int allow_threads

      Si se trata de "0", el módulo "threading" del subintérprete no
      creará subprocesos. De lo contrario, se permiten los
      subprocesos.

   int allow_daemon_threads

      Si se trata de "0", el módulo "threading" del subintérprete no
      creará subprocesos de demonio. De lo contrario, se permiten
      subprocesos de demonio (siempre que "allow_threads" no sea
      cero).

   int check_multi_interp_extensions

      Si se trata de "0", se podrán importar todos los módulos de
      extensión, incluidos los módulos heredados (inicio monofásico),
      en cualquier subproceso en el que el subintérprete esté activo
      en ese momento. De lo contrario, solo se podrán importar los
      módulos de extensión de inicio multifásico (consulte **PEP
      489**). (Consulte también "Py_mod_multiple_interpreters").

      Debe ser "1" (distinto de cero) si "use_main_obmalloc" es "0".

   int gil

      Esto determina el funcionamiento del GIL para el subintérprete.
      Puede ser uno de los siguientes:

      PyInterpreterConfig_DEFAULT_GIL

         Utilice la selección predeterminada
         ("PyInterpreterConfig_SHARED_GIL").

      PyInterpreterConfig_SHARED_GIL

         Utilice (comparta) el GIL del intérprete principal.

      PyInterpreterConfig_OWN_GIL

         Utilice el GIL propio del subintérprete.

      Si es "PyInterpreterConfig_OWN_GIL", entonces
      "PyInterpreterConfig.use_main_obmalloc" debe ser "0".

PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)

   Crea un nuevo subinterprete. Este es un entorno (casi) totalmente
   separado para la ejecución de código Python. En particular, el
   nuevo intérprete tiene versiones separadas e independientes de
   todos los módulos importados, incluidos los módulos fundamentales
   "builtins", "__main__" y "sys". La tabla de módulos cargados
   ("sys.modules") y la ruta de búsqueda del módulo ("sys.path")
   también están separados. El nuevo entorno no tiene variable
   "sys.argv". Tiene nuevos objetos de archivo de flujo de E/S
   estándar "sys.stdin", "sys.stdout" y "sys.stderr" (sin embargo,
   estos se refieren a los mismos descriptores de archivo
   subyacentes).

   El *config* dado controla las opciones con las que se inicializa el
   intérprete.

   Upon success, *tstate_p* will be set to the first *thread state*
   created in the new sub-interpreter.  This thread state is
   *attached*. Note that no actual thread is created; see the
   discussion of thread states below.  If creation of the new
   interpreter is unsuccessful, *tstate_p* is set to "NULL"; no
   exception is set since the exception state is stored in the
   *attached thread state*, which might not exist.

   Like all other Python/C API functions, an *attached thread state*
   must be present before calling this function, but it might be
   detached upon returning. On success, the returned thread state will
   be *attached*. If the sub-interpreter is created with its own *GIL*
   then the *attached thread state* of the calling interpreter will be
   detached. When the function returns, the new interpreter's *thread
   state* will be *attached* to the current thread and the previous
   interpreter's *attached thread state* will remain detached.

   Added in version 3.12.

   Los subintérpretes son más eficaces cuando están aislados unos de
   otros y con ciertas funciones restringidas:

      PyInterpreterConfig config = {
          .use_main_obmalloc = 0,
          .allow_fork = 0,
          .allow_exec = 0,
          .allow_threads = 1,
          .allow_daemon_threads = 0,
          .check_multi_interp_extensions = 1,
          .gil = PyInterpreterConfig_OWN_GIL,
      };
      PyThreadState *tstate = NULL;
      PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
      if (PyStatus_Exception(status)) {
          Py_ExitStatusException(status);
      }

   Tenga en cuenta que la configuración se utiliza solo brevemente y
   no se modifica. Durante la inicialización, los valores de la
   configuración se convierten en varios valores "PyInterpreterState".
   Es posible que se almacene una copia de solo lectura de la
   configuración internamente en el "PyInterpreterState".

   Los módulos de extensión se comparten entre (sub) intérpretes de la
   siguiente manera:

   * Para módulos que usan inicialización multifase, por ejemplo
     "PyModule_FromDefAndSpec()", se crea e inicializa un objeto de
     módulo separado para cada intérprete. Solo las variables
     estáticas y globales de nivel C se comparten entre estos objetos
     de módulo.

   * Para módulos que utilizan inicialización monofásica, por ejemplo
     "PyModule_Create()", la primera vez que se importa una extensión
     en particular, se inicializa normalmente y una copia
     (superficial) del diccionario de su módulo se guarda. Cuando otro
     (sub) intérprete importa la misma extensión, se inicializa un
     nuevo módulo y se llena con el contenido de esta copia; no se
     llama a la función "init" de la extensión. Los objetos en el
     diccionario del módulo terminan compartidos entre (sub)
     intérpretes, lo que puede causar un comportamiento no deseado
     (ver Errores y advertencias (Bugs and caveats) a continuación).

     Tenga en cuenta que esto es diferente de lo que sucede cuando se
     importa una extensión después de que el intérprete se haya
     reiniciado por completo llamando a "Py_FinalizeEx()" y
     "Py_Initialize()"; en ese caso, la función "initmodule" de la
     extensión *es* llamada nuevamente. Al igual que con la
     inicialización de múltiples fases, esto significa que solo se
     comparten variables estáticas y globales de nivel C entre estos
     módulos.

PyThreadState *Py_NewInterpreter(void)
    * Part of the Stable ABI.*

   Cree un nuevo subintérprete. Básicamente, se trata de un envoltorio
   de "Py_NewInterpreterFromConfig()" con una configuración que
   conserva el comportamiento existente. El resultado es un
   subintérprete no aislado que comparte el GIL del intérprete
   principal, permite fork/exec, permite subprocesos de demonio y
   permite módulos de inicialización monofásicos.

void Py_EndInterpreter(PyThreadState *tstate)
    * Part of the Stable ABI.*

   Destroy the (sub-)interpreter represented by the given *thread
   state*. The given thread state must be *attached*. When the call
   returns, there will be no *attached thread state*. All thread
   states associated with this interpreter are destroyed.

   "Py_FinalizeEx()" destruirá todos los subintérpretes que no hayan
   sido destruidos explícitamente en ese momento.


Un GIL por intérprete
---------------------

Using "Py_NewInterpreterFromConfig()" you can create a sub-interpreter
that is completely isolated from other interpreters, including having
its own GIL.  The most important benefit of this isolation is that
such an interpreter can execute Python code without being blocked by
other interpreters or blocking any others.  Thus a single Python
process can truly take advantage of multiple CPU cores when running
Python code.  The isolation also encourages a different approach to
concurrency than that of just using threads. (See **PEP 554** and
**PEP 684**.)

El uso de un intérprete aislado requiere vigilancia para preservar ese
aislamiento. Esto significa especialmente no compartir ningún objeto o
estado mutable sin garantías sobre la seguridad de los subprocesos.
Incluso los objetos que de otro modo serían inmutables (por ejemplo,
"None", "(1, 5)") normalmente no se pueden compartir debido al
recuento de referencias. Un enfoque simple pero menos eficiente para
evitar esto es usar un bloqueo global alrededor de todo uso de algún
estado (u objeto). Alternativamente, los objetos efectivamente
inmutables (como números enteros o cadenas) se pueden hacer seguros a
pesar de sus recuentos de referencias al convertirlos en *immortal*.
De hecho, esto se ha hecho para los singletons integrados, los números
enteros pequeños y una serie de otros objetos integrados.

Si preserva el aislamiento, tendrá acceso a una computación
multinúcleo adecuada sin las complicaciones que conlleva el uso de
subprocesos libres. Si no preserva el aislamiento, se expondrá a todas
las consecuencias del uso de subprocesos libres, incluidas las
carreras y los fallos difíciles de depurar.

Aparte de eso, uno de los principales desafíos de usar varios
intérpretes aislados es cómo comunicarse entre ellos de forma segura
(sin romper el aislamiento) y eficiente. El entorno de ejecución y la
biblioteca estándar aún no ofrecen ningún enfoque estándar para esto.
Un futuro módulo de la biblioteca estándar ayudaría a mitigar el
esfuerzo de preservar el aislamiento y expondría herramientas
efectivas para comunicar (y compartir) datos entre intérpretes.

Added in version 3.12.


Errores y advertencias
----------------------

Debido a que los subinterpretes (y el intérprete principal) son parte
del mismo proceso, el aislamiento entre ellos no es perfecto --- por
ejemplo, usando operaciones de archivos de bajo nivel como
"os.close()" pueden (accidentalmente o maliciosamente) afectar los
archivos abiertos del otro. Debido a la forma en que las extensiones
se comparten entre (sub) intérpretes, algunas extensiones pueden no
funcionar correctamente; esto es especialmente probable cuando se
utiliza la inicialización monofásica o las variables globales
(estáticas). Es posible insertar objetos creados en un subinterprete
en un espacio de nombres de otro (sub) intérprete; Esto debe evitarse
si es posible.

Se debe tener especial cuidado para evitar compartir funciones,
métodos, instancias o clases definidas por el usuario entre los
subinterpretes, ya que las operaciones de importación ejecutadas por
dichos objetos pueden afectar el diccionario (sub-) intérprete
incorrecto de los módulos cargados. Es igualmente importante evitar
compartir objetos desde los que se pueda acceder a lo anterior.

También tenga en cuenta que la combinación de esta funcionalidad con
"PyGILState_*" APIs es delicada, porque estas APIs suponen una
biyección entre los estados de hilo de Python e hilos a nivel del
sistema operativo, una suposición rota por la presencia de
subinterpretes. Se recomienda encarecidamente que no cambie los
subinterpretes entre un par de llamadas coincidentes
"PyGILState_Ensure()" y "PyGILState_Release()". Además, las
extensiones (como "ctypes") que usan estas APIs para permitir la
llamada de código Python desde hilos no creados por Python
probablemente se rompan cuando se usan subinterpretes.


Notificaciones asincrónicas
===========================

Se proporciona un mecanismo para hacer notificaciones asincrónicas al
hilo principal del intérprete. Estas notificaciones toman la forma de
un puntero de función y un argumento de puntero nulo.

int Py_AddPendingCall(int (*func)(void*), void *arg)
    * Part of the Stable ABI.*

   Programa una función para que se llame desde el hilo principal del
   intérprete. En caso de éxito, se retorna "0" y se pone en cola
   *func* para ser llamado en el hilo principal. En caso de fallo, se
   retorna "-1" sin establecer ninguna excepción.

   Cuando se puso en cola con éxito, *func* será *eventualmente*
   invocado desde el hilo principal del intérprete con el argumento
   *arg*. Se llamará de forma asincrónica con respecto al código
   Python que se ejecuta normalmente, pero con ambas condiciones
   cumplidas:

   * en un límite *bytecode*;

   * with the main thread holding an *attached thread state* (*func*
     can therefore use the full C API).

   *func* must return "0" on success, or "-1" on failure with an
   exception set.  *func* won't be interrupted to perform another
   asynchronous notification recursively, but it can still be
   interrupted to switch threads if the *thread state* is detached.

   This function doesn't need an *attached thread state*. However, to
   call this function in a subinterpreter, the caller must have an
   *attached thread state*. Otherwise, the function *func* can be
   scheduled to be called from the wrong interpreter.

   Advertencia:

     Esta es una función de bajo nivel, solo útil para casos muy
     especiales. No hay garantía de que *func* se llame lo más rápido
     posible. Si el hilo principal está ocupado ejecutando una llamada
     al sistema, no se llamará *func* antes de que vuelva la llamada
     del sistema. Esta función generalmente **no** es adecuada para
     llamar a código Python desde hilos C arbitrarios. En su lugar,
     use PyGILState API.

   Added in version 3.1.

   Distinto en la versión 3.9: Si esta función se llama en un
   subinterprete, la función *func* ahora está programada para ser
   llamada desde el subinterprete, en lugar de ser llamada desde el
   intérprete principal. Cada subinterprete ahora tiene su propia
   lista de llamadas programadas.

   Distinto en la versión 3.12: This function now always schedules
   *func* to be run in the main interpreter.

int Py_MakePendingCalls(void)
    * Part of the Stable ABI.*

   Execute all pending calls. This is usually executed automatically
   by the interpreter.

   This function returns "0" on success, and returns "-1" with an
   exception set on failure.

   If this is not called in the main thread of the main interpreter,
   this function does nothing and returns "0". The caller must hold an
   *attached thread state*.

   Added in version 3.1.

   Distinto en la versión 3.12: This function only runs pending calls
   in the main interpreter.


Perfilado y Rastreo
===================

El intérprete de Python proporciona soporte de bajo nivel para
adjuntar funciones de creación de perfiles y seguimiento de ejecución.
Estos se utilizan para herramientas de análisis de perfiles,
depuración y cobertura.

Esta interfaz C permite que el código de perfilado o rastreo evite la
sobrecarga de llamar a través de objetos invocables a nivel de Python,
haciendo una llamada directa a la función C en su lugar. Los atributos
esenciales de la instalación no han cambiado; la interfaz permite
instalar funciones de rastreo por hilos, y los eventos básicos
informados a la función de rastreo son los mismos que se informaron a
las funciones de rastreo a nivel de Python en versiones anteriores.

typedef int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)

   El tipo de la función de seguimiento registrada mediante
   "PyEval_SetProfile()" y "PyEval_SetTrace()". El primer parámetro es
   el objeto pasado a la función de registro como *obj*, *frame* es el
   objeto de marco al que pertenece el evento, *what* es una de las
   constantes "PyTrace_CALL", "PyTrace_EXCEPTION", "PyTrace_LINE",
   "PyTrace_RETURN", "PyTrace_C_CALL", "PyTrace_C_EXCEPTION",
   "PyTrace_C_RETURN" o "PyTrace_OPCODE", y *arg* depende del valor de
   *what*:

   +---------------------------------+------------------------------------------+
   | Valor de *what*                 | Significado de *arg*                     |
   |=================================|==========================================|
   | "PyTrace_CALL"                  | Siempre "Py_None".                       |
   +---------------------------------+------------------------------------------+
   | "PyTrace_EXCEPTION"             | Información de excepción retornada por   |
   |                                 | "sys.exc_info()".                        |
   +---------------------------------+------------------------------------------+
   | "PyTrace_LINE"                  | Siempre "Py_None".                       |
   +---------------------------------+------------------------------------------+
   | "PyTrace_RETURN"                | Valor retornado al que llama, o "NULL"   |
   |                                 | si es causado por una excepción.         |
   +---------------------------------+------------------------------------------+
   | "PyTrace_C_CALL"                | Objeto función que se llaman.            |
   +---------------------------------+------------------------------------------+
   | "PyTrace_C_EXCEPTION"           | Objeto función que se llaman.            |
   +---------------------------------+------------------------------------------+
   | "PyTrace_C_RETURN"              | Objeto función que se llaman.            |
   +---------------------------------+------------------------------------------+
   | "PyTrace_OPCODE"                | Siempre "Py_None".                       |
   +---------------------------------+------------------------------------------+

int PyTrace_CALL

   El valor del parámetro *what* para una función "Py_tracefunc"
   cuando se informa una nueva llamada a una función o método, o una
   nueva entrada en un generador. Tenga en cuenta que la creación del
   iterador para una función de generador no se informa ya que no hay
   transferencia de control al código de bytes de Python en la marco
   correspondiente.

int PyTrace_EXCEPTION

   El valor del parámetro *what* para una función "Py_tracefunc"
   cuando se ha producido una excepción. La función de devolución de
   llamada se llama con este valor para *what* cuando después de que
   se procese cualquier bytecode, después de lo cual la excepción se
   establece dentro del marco que se está ejecutando. El efecto de
   esto es que a medida que la propagación de la excepción hace que la
   pila de Python se desenrolle, el retorno de llamada se llama al
   retornar a cada marco a medida que se propaga la excepción. Solo
   las funciones de rastreo reciben estos eventos; el perfilador
   (*profiler*) no los necesita.

int PyTrace_LINE

   El valor que se pasa como parámetro *what* a una función
   "Py_tracefunc" (pero no a una función de creación de perfiles)
   cuando se informa un evento de número de línea. Se puede desactivar
   para un marco configurando "f_trace_lines" en *0* en ese marco.

int PyTrace_RETURN

   El valor para el parámetro *what* para "Py_tracefunc" funciona
   cuando una llamada está por regresar.

int PyTrace_C_CALL

   El valor del parámetro *what* para "Py_tracefunc" funciona cuando
   una función C está a punto de ser invocada.

int PyTrace_C_EXCEPTION

   El valor del parámetro *what* para funciones "Py_tracefunc" cuando
   una función C ha lanzado una excepción.

int PyTrace_C_RETURN

   El valor del parámetro *what* para "Py_tracefunc" funciona cuando
   una función C ha retornado.

int PyTrace_OPCODE

   El valor del parámetro *what* para las funciones "Py_tracefunc"
   (pero no para las funciones de creación de perfiles) cuando está a
   punto de ejecutarse un nuevo código de operación. Este evento no se
   emite de forma predeterminada: debe solicitarse explícitamente
   configurando "f_trace_opcodes" en *1* en el marco.

void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)

   Establezca la función de perfilador en *func*. El parámetro *obj*
   se pasa a la función como su primer parámetro y puede ser cualquier
   objeto Python o "NULL". Si la función de perfilador necesita
   mantener el estado, el uso de un valor diferente para *obj* para
   cada subproceso proporciona un lugar conveniente y seguro para
   subprocesos donde almacenarlo. La función de perfilador se llama
   para todos los eventos monitoreados excepto "PyTrace_LINE",
   "PyTrace_OPCODE" y "PyTrace_EXCEPTION".

   Consulte también la función "sys.setprofile()".

   The caller must have an *attached thread state*.

void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)

   Como "PyEval_SetProfile()", pero establece la función de perfil en
   todos los subprocesos en ejecución que pertenecen al intérprete
   actual en lugar de configurarla solo en el subproceso actual.

   The caller must have an *attached thread state*.

   Al igual que "PyEval_SetProfile()", esta función ignora cualquier
   excepción generada al configurar las funciones de perfil en todos
   los subprocesos.

Added in version 3.12.

void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)

   Establezca la función de seguimiento en *func*. Es similar a
   "PyEval_SetProfile()", excepto que la función de seguimiento recibe
   eventos de número de línea y eventos por código de operación, pero
   no recibe ningún evento relacionado con los objetos de función C
   que se están llamando. Cualquier función de seguimiento registrada
   con "PyEval_SetTrace()" no recibirá "PyTrace_C_CALL",
   "PyTrace_C_EXCEPTION" o "PyTrace_C_RETURN" como valor para el
   parámetro *what*.

   Consulte también la función "sys.settrace()".

   The caller must have an *attached thread state*.

void PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *obj)

   Como "PyEval_SetTrace()", pero establece la función de seguimiento
   en todos los subprocesos en ejecución que pertenecen al intérprete
   actual en lugar de configurarla solo en el subproceso actual.

   The caller must have an *attached thread state*.

   Al igual que "PyEval_SetTrace()", esta función ignora cualquier
   excepción generada al configurar las funciones de seguimiento en
   todos los subprocesos.

Added in version 3.12.


Rastreo de referencia
=====================

Added in version 3.13.

typedef int (*PyRefTracer)(PyObject*, int event, void *data)

   El tipo de la función de seguimiento registrada mediante
   "PyRefTracer_SetTracer()". El primer parámetro es un objeto Python
   que se acaba de crear (cuando **event** se establece en
   "PyRefTracer_CREATE") o que está a punto de destruirse (cuando
   **event** se establece en "PyRefTracer_DESTROY"). El argumento
   **data** es el puntero opaco que se proporcionó cuando se llamó a
   "PyRefTracer_SetTracer()".

Added in version 3.13.

int PyRefTracer_CREATE

   El valor del parámetro *event* a "PyRefTracer" funciona cuando se
   ha creado un objeto Python.

int PyRefTracer_DESTROY

   El valor del parámetro *event* a "PyRefTracer" funciona cuando se
   ha destruido un objeto Python.

int PyRefTracer_SetTracer(PyRefTracer tracer, void *data)

   Registra una función de rastreo de referencia. La función se
   llamará cuando se haya creado un nuevo Python o cuando se vaya a
   destruir un objeto. Si se proporciona **data**, debe ser un puntero
   opaco que se proporcionará cuando se llame a la función de rastreo.
   Devuelve "0" en caso de éxito. Establece una excepción y devuelve
   "-1" en caso de error.

   Not that tracer functions **must not** create Python objects inside
   or otherwise the call will be re-entrant. The tracer also **must
   not** clear any existing exception or set an exception.  A *thread
   state* will be active every time the tracer function is called.

   There must be an *attached thread state* when calling this
   function.

Added in version 3.13.

PyRefTracer PyRefTracer_GetTracer(void **data)

   Obtenga la función de trazador de referencia registrada y el valor
   del puntero de datos opacos que se registró cuando se llamó a
   "PyRefTracer_SetTracer()". Si no se registró ningún trazador, esta
   función devolverá NULL y establecerá el puntero **data** en NULL.

   There must be an *attached thread state* when calling this
   function.

Added in version 3.13.


Soporte avanzado del depurador
==============================

Estas funciones solo están destinadas a ser utilizadas por
herramientas de depuración avanzadas.

PyInterpreterState *PyInterpreterState_Head()

   Retorna el objeto de estado del intérprete al principio de la lista
   de todos esos objetos.

PyInterpreterState *PyInterpreterState_Main()

   Retorna el objeto de estado del intérprete principal.

PyInterpreterState *PyInterpreterState_Next(PyInterpreterState *interp)

   Retorna el siguiente objeto de estado de intérprete después de
   *interp* de la lista de todos esos objetos.

PyThreadState *PyInterpreterState_ThreadHead(PyInterpreterState *interp)

   Retorna el puntero al primer objeto "PyThreadState" en la lista de
   hilos asociados con el intérprete *interp*.

PyThreadState *PyThreadState_Next(PyThreadState *tstate)

   Retorna el siguiente objeto de estado del hilo después de *tstate*
   de la lista de todos los objetos que pertenecen al mismo objeto
   "PyInterpreterState".


Soporte de almacenamiento local de hilo
=======================================

El intérprete de Python proporciona soporte de bajo nivel para el
almacenamiento local de hilos (TLS) que envuelve la implementación de
TLS nativa subyacente para admitir la API de almacenamiento local de
hilos de nivel Python ("threading.local"). Las APIs de nivel CPython C
son similares a las ofrecidas por pthreads y Windows: use una clave de
hilo y funciones para asociar un valor de void* por hilo.

A *thread state* does *not* need to be *attached* when calling these
functions; they suppl their own locking.

Tenga en cuenta que "Python.h" no incluye la declaración de las API de
TLS, debe incluir "pythread.h" para usar el almacenamiento local de
hilos.

Nota:

  Ninguna de estas funciones API maneja la administración de memoria
  en nombre de los valores void*. Debe asignarlos y desasignarlos
  usted mismo. Si los valores void* son PyObject*, estas funciones
  tampoco realizan operaciones de conteo de referencias en ellos.


API de almacenamiento específico de hilo (TSS, *Thread Specific Storage*)
-------------------------------------------------------------------------

La API de TSS se introduce para reemplazar el uso de la API TLS
existente dentro del intérprete de CPython. Esta API utiliza un nuevo
tipo "Py_tss_t" en lugar de int para representar las claves del hilo.

Added in version 3.7.

Ver también:

  "Una nueva C-API para *Thread-Local Storage* en CPython" (**PEP
  539**)

type Py_tss_t

   Esta estructura de datos representa el estado de una clave del
   hilo, cuya definición puede depender de la implementación de TLS
   subyacente, y tiene un campo interno que representa el estado de
   inicialización de la clave. No hay miembros públicos en esta
   estructura.

   Cuando Py_LIMITED_API no está definido, la asignación estática de
   este tipo por "Py_tss_NEEDS_INIT" está permitida.

Py_tss_NEEDS_INIT

   Esta macro se expande al inicializador para variables "Py_tss_t".
   Tenga en cuenta que esta macro no se definirá con Py_LIMITED_API.


Asignación dinámica
~~~~~~~~~~~~~~~~~~~

Asignación dinámica de "Py_tss_t", requerida en los módulos de
extensión construidos con Py_LIMITED_API, donde la asignación estática
de este tipo no es posible debido a que su implementación es opaca en
el momento de la compilación.

Py_tss_t *PyThread_tss_alloc()
    * Part of the Stable ABI since version 3.7.*

   Retorna un valor que es el mismo estado que un valor inicializado
   con "Py_tss_NEEDS_INIT", o "NULL" en caso de falla de asignación
   dinámica.

void PyThread_tss_free(Py_tss_t *key)
    * Part of the Stable ABI since version 3.7.*

   Libera la *clave* asignada por "PyThread_tss_alloc()", después de
   llamar por primera vez "PyThread_tss_delete()" para asegurarse de
   que los hilos locales asociados no hayan sido asignados. Esto es un
   no-op si el argumento *clave* es "NULL".

   Nota:

     Una clave liberada se convierte en un puntero colgante. Debería
     restablecer la clave a "NULL".


Métodos
~~~~~~~

El parámetro *key* de estas funciones no debe ser "NULL". Además, los
comportamientos de "PyThread_tss_set()" y "PyThread_tss_get()" no
están definidos si el "Py_tss_t" dado no ha sido inicializado por
"PyThread_tss_create()".

int PyThread_tss_is_created(Py_tss_t *key)
    * Part of the Stable ABI since version 3.7.*

   Retorna un valor distinto de cero si "Py_tss_t" ha sido
   inicializado por "PyThread_tss_create()".

int PyThread_tss_create(Py_tss_t *key)
    * Part of the Stable ABI since version 3.7.*

   Retorna un valor cero en la inicialización exitosa de una clave
   TSS. El comportamiento no está definido si el valor señalado por el
   argumento *key* no se inicializa con "Py_tss_NEEDS_INIT". Esta
   función se puede invocar repetidamente en la misma tecla: llamarla
   a una tecla ya inicializada es un *no-op* e inmediatamente retorna
   el éxito.

void PyThread_tss_delete(Py_tss_t *key)
    * Part of the Stable ABI since version 3.7.*

   Destruye una clave TSS para olvidar los valores asociados con la
   clave en todos los hilos y cambie el estado de inicialización de la
   clave a no inicializado. Una clave destruida se puede inicializar
   nuevamente mediante "PyThread_tss_create()". Esta función se puede
   invocar repetidamente en la misma llave; llamarla en una llave ya
   destruida es un *no-op*.

int PyThread_tss_set(Py_tss_t *key, void *value)
    * Part of the Stable ABI since version 3.7.*

   Retorna un valor cero para indicar la asociación exitosa de un
   valor a void* con una clave TSS en el hilo actual. Cada hilo tiene
   un mapeo distinto de la clave a un valor void*.

void *PyThread_tss_get(Py_tss_t *key)
    * Part of the Stable ABI since version 3.7.*

   Retorna el valor void* asociado con una clave TSS en el hilo
   actual. Esto retorna "NULL" si no hay ningún valor asociado con la
   clave en el hilo actual.


API de almacenamiento local de hilos (TLS, *Thread Local Storage*)
------------------------------------------------------------------

Obsoleto desde la versión 3.7: Esta API es reemplazada por API de
Almacenamiento Específico de Hilos (TSS, por sus significado en inglés
*Thread Specific Storage*).

Nota:

  Esta versión de la API no es compatible con plataformas donde la
  clave TLS nativa se define de una manera que no se puede transmitir
  de forma segura a "int". En tales plataformas,
  "PyThread_create_key()" regresará inmediatamente con un estado de
  falla, y las otras funciones TLS serán no operativas en tales
  plataformas.

Debido al problema de compatibilidad mencionado anteriormente, esta
versión de la API no debe usarse en código nuevo.

int PyThread_create_key()
    * Part of the Stable ABI.*

void PyThread_delete_key(int key)
    * Part of the Stable ABI.*

int PyThread_set_key_value(int key, void *value)
    * Part of the Stable ABI.*

void *PyThread_get_key_value(int key)
    * Part of the Stable ABI.*

void PyThread_delete_key_value(int key)
    * Part of the Stable ABI.*

void PyThread_ReInitTLS()
    * Part of the Stable ABI.*


Primitivas de sincronización
============================

La C-API proporciona un bloqueo de exclusión mutua básico.

type PyMutex

   Un bloqueo de exclusión mutua. El "PyMutex" debe inicializarse a
   cero para representar el estado desbloqueado. Por ejemplo:

      PyMutex mutex = {0};

   Las instancias de "PyMutex" no se deben copiar ni mover. Tanto el
   contenido como la dirección de un "PyMutex" son significativos y
   deben permanecer en una ubicación fija y escribible en la memoria.

   Nota:

     Actualmente, un "PyMutex" ocupa un byte, pero el tamaño debe
     considerarse inestable. El tamaño puede cambiar en futuras
     versiones de Python sin un período de desuso.

   Added in version 3.13.

void PyMutex_Lock(PyMutex *m)

   Lock mutex *m*.  If another thread has already locked it, the
   calling thread will block until the mutex is unlocked.  While
   blocked, the thread will temporarily detach the *thread state* if
   one exists.

   Added in version 3.13.

void PyMutex_Unlock(PyMutex *m)

   Desbloquee el mutex *m*. El mutex debe estar bloqueado; de lo
   contrario, la función emitirá un error fatal.

   Added in version 3.13.

int PyMutex_IsLocked(PyMutex *m)

   Returns non-zero if the mutex *m* is currently locked, zero
   otherwise.

   Nota:

     This function is intended for use in assertions and debugging
     only and should not be used to make concurrency control
     decisions, as the lock state may change immediately after the
     check.

   Added in version 3.14.


API de sección crítica de Python
--------------------------------

La API de sección crítica proporciona una capa de prevención de
bloqueos sobre los bloqueos por objeto para *free-threaded* CPython.
Su objetivo es reemplazar la dependencia de *global interpreter lock*
y no se pueden realizar operaciones en versiones de Python con el
bloqueo del intérprete global.

Critical sections are intended to be used for custom types implemented
in C-API extensions. They should generally not be used with built-in
types like "list" and "dict" because their public C-APIs already use
critical sections internally, with the notable exception of
"PyDict_Next()", which requires critical section to be acquired
externally.

Critical sections avoid deadlocks by implicitly suspending active
critical sections, hence, they do not provide exclusive access such as
provided by traditional locks like "PyMutex".  When a critical section
is started, the per-object lock for the object is acquired. If the
code executed inside the critical section calls C-API functions then
it can suspend the critical section thereby releasing the per-object
lock, so other threads can acquire the per-object lock for the same
object.

Variants that accept "PyMutex" pointers rather than Python objects are
also available. Use these variants to start a critical section in a
situation where there is no "PyObject" -- for example, when working
with a C type that does not extend or wrap "PyObject" but still needs
to call into the C API in a manner that might lead to deadlocks.

Las funciones y estructuras que utilizan las macros se exponen para
los casos en los que las macros de C no están disponibles. Solo se
deben utilizar como en las expansiones de macros indicadas. Tenga en
cuenta que los tamaños y contenidos de las estructuras pueden cambiar
en futuras versiones de Python.

Nota:

  Las operaciones que necesitan bloquear dos objetos a la vez deben
  utilizar "Py_BEGIN_CRITICAL_SECTION2". *cannot* utiliza secciones
  críticas anidadas para bloquear más de un objeto a la vez, ya que la
  sección crítica interna puede suspender las secciones críticas
  externas. Esta API no proporciona una manera de bloquear más de dos
  objetos a la vez.

Ejemplo de uso:

   static PyObject *
   set_field(MyObject *self, PyObject *value)
   {
      Py_BEGIN_CRITICAL_SECTION(self);
      Py_SETREF(self->field, Py_XNewRef(value));
      Py_END_CRITICAL_SECTION();
      Py_RETURN_NONE;
   }

In the above example, "Py_SETREF" calls "Py_DECREF", which can call
arbitrary code through an object's deallocation function.  The
critical section API avoids potential deadlocks due to reentrancy and
lock ordering by allowing the runtime to temporarily suspend the
critical section if the code triggered by the finalizer blocks and
calls "PyEval_SaveThread()".

Py_BEGIN_CRITICAL_SECTION(op)

   Adquiere el bloqueo por objeto para el objeto *op* y comienza una
   sección crítica.

   En la compilación de subprocesos libres, esta macro se expande a:

      {
          PyCriticalSection _py_cs;
          PyCriticalSection_Begin(&_py_cs, (PyObject*)(op))

   En la compilación predeterminada, esta macro se expande a "{".

   Added in version 3.13.

Py_BEGIN_CRITICAL_SECTION_MUTEX(m)

   Locks the mutex *m* and begins a critical section.

   En la compilación de subprocesos libres, esta macro se expande a:

      {
           PyCriticalSection _py_cs;
           PyCriticalSection_BeginMutex(&_py_cs, m)

   Note that unlike "Py_BEGIN_CRITICAL_SECTION", there is no cast for
   the argument of the macro - it must be a "PyMutex" pointer.

   On the default build, this macro expands to "{".

   Added in version 3.14.

Py_END_CRITICAL_SECTION()

   Finaliza la sección crítica y libera el bloqueo por objeto.

   En la compilación de subprocesos libres, esta macro se expande a:

          PyCriticalSection_End(&_py_cs);
      }

   En la compilación predeterminada, esta macro se expande a "}".

   Added in version 3.13.

Py_BEGIN_CRITICAL_SECTION2(a, b)

   Adquiere los bloqueos por objeto para los objetos *a* y *b* y
   comienza una sección crítica. Los bloqueos se adquieren en un orden
   coherente (la dirección más baja primero) para evitar bloqueos en
   el orden de bloqueo.

   En la compilación de subprocesos libres, esta macro se expande a:

      {
          PyCriticalSection2 _py_cs2;
          PyCriticalSection2_Begin(&_py_cs2, (PyObject*)(a), (PyObject*)(b))

   En la compilación predeterminada, esta macro se expande a "{".

   Added in version 3.13.

Py_BEGIN_CRITICAL_SECTION2_MUTEX(m1, m2)

   Locks the mutexes *m1* and *m2* and begins a critical section.

   En la compilación de subprocesos libres, esta macro se expande a:

      {
           PyCriticalSection2 _py_cs2;
           PyCriticalSection2_BeginMutex(&_py_cs2, m1, m2)

   Note that unlike "Py_BEGIN_CRITICAL_SECTION2", there is no cast for
   the arguments of the macro - they must be "PyMutex" pointers.

   On the default build, this macro expands to "{".

   Added in version 3.14.

Py_END_CRITICAL_SECTION2()

   Finaliza la sección crítica y libera los bloqueos por objeto.

   En la compilación de subprocesos libres, esta macro se expande a:

          PyCriticalSection2_End(&_py_cs2);
      }

   En la compilación predeterminada, esta macro se expande a "}".

   Added in version 3.13.


Legacy Locking APIs
-------------------

These APIs are obsolete since Python 3.13 with the introduction of
"PyMutex".

Distinto en la versión 3.15: These APIs are now a simple wrapper
around "PyMutex".

type PyThread_type_lock

   A pointer to a mutual exclusion lock.

type PyLockStatus

   The result of acquiring a lock with a timeout.

   enumerator PY_LOCK_FAILURE

      Failed to acquire the lock.

   enumerator PY_LOCK_ACQUIRED

      The lock was successfully acquired.

   enumerator PY_LOCK_INTR

      The lock was interrupted by a signal.

PyThread_type_lock PyThread_allocate_lock(void)
    * Part of the Stable ABI.*

   Allocate a new lock.

   On success, this function returns a lock; on failure, this function
   returns "0" without an exception set.

   The caller does not need to hold an *attached thread state*.

   Distinto en la versión 3.15: This function now always uses
   "PyMutex". In prior versions, this would use a lock provided by the
   operating system.

void PyThread_free_lock(PyThread_type_lock lock)
    * Part of the Stable ABI.*

   Destroy *lock*. The lock should not be held by any thread when
   calling this.

   The caller does not need to hold an *attached thread state*.

PyLockStatus PyThread_acquire_lock_timed(PyThread_type_lock lock, long long microseconds, int intr_flag)
    * Part of the Stable ABI.*

   Acquire *lock* with a timeout.

   This will wait for *microseconds* microseconds to acquire the lock.
   If the timeout expires, this function returns "PY_LOCK_FAILURE". If
   *microseconds* is "-1", this will wait indefinitely until the lock
   has been released.

   If *intr_flag* is "1", acquiring the lock may be interrupted by a
   signal, in which case this function returns "PY_LOCK_INTR". Upon
   interruption, it's generally expected that the caller makes a call
   to "Py_MakePendingCalls()" to propagate an exception to Python
   code.

   If the lock is successfully acquired, this function returns
   "PY_LOCK_ACQUIRED".

   The caller does not need to hold an *attached thread state*.

int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
    * Part of the Stable ABI.*

   Acquire *lock*.

   If *waitflag* is "1" and another thread currently holds the lock,
   this function will wait until the lock can be acquired and will
   always return "1".

   If *waitflag* is "0" and another thread holds the lock, this
   function will not wait and instead return "0". If the lock is not
   held by any other thread, then this function will acquire it and
   return "1".

   Unlike "PyThread_acquire_lock_timed()", acquiring the lock cannot
   be interrupted by a signal.

   The caller does not need to hold an *attached thread state*.

int PyThread_release_lock(PyThread_type_lock lock)
    * Part of the Stable ABI.*

   Release *lock*. If *lock* is not held, then this function issues a
   fatal error.

   The caller does not need to hold an *attached thread state*.


Operating System Thread APIs
============================

PYTHREAD_INVALID_THREAD_ID

   Sentinel value for an invalid thread ID.

   This is currently equivalent to "(unsigned long)-1".

unsigned long PyThread_start_new_thread(void (*func)(void*), void *arg)
    * Part of the Stable ABI.*

   Start function *func* in a new thread with argument *arg*. The
   resulting thread is not intended to be joined.

   *func* must not be "NULL", but *arg* may be "NULL".

   On success, this function returns the identifier of the new thread;
   on failure, this returns "PYTHREAD_INVALID_THREAD_ID".

   The caller does not need to hold an *attached thread state*.

unsigned long PyThread_get_thread_ident(void)
    * Part of the Stable ABI.*

   Return the identifier of the current thread, which will never be
   zero.

   This function cannot fail, and the caller does not need to hold an
   *attached thread state*.

   Ver también: "threading.get_ident()"

PyObject *PyThread_GetInfo(void)
    * Part of the Stable ABI since version 3.3.*

   Get general information about the current thread in the form of a
   struct sequence object. This information is accessible as
   "sys.thread_info" in Python.

   On success, this returns a new *strong reference* to the thread
   information; on failure, this returns "NULL" with an exception set.

   The caller must hold an *attached thread state*.

PY_HAVE_THREAD_NATIVE_ID

   This macro is defined when the system supports native thread IDs.

unsigned long PyThread_get_thread_native_id(void)
    * Part of the Stable ABI on platforms with native thread IDs.*

   Get the native identifier of the current thread as it was assigned
   by the operating system's kernel, which will never be less than
   zero.

   This function is only available when "PY_HAVE_THREAD_NATIVE_ID" is
   defined.

   This function cannot fail, and the caller does not need to hold an
   *attached thread state*.

   Ver también: "threading.get_native_id()"

void PyThread_exit_thread(void)
    * Part of the Stable ABI.*

   Terminate the current thread. This function is generally considered
   unsafe and should be avoided. It is kept solely for backwards
   compatibility.

   This function is only safe to call if all functions in the full
   call stack are written to safely allow it.

   Advertencia:

     If the current system uses POSIX threads (also known as
     "pthreads"), this calls *pthread_exit(3)*, which attempts to
     unwind the stack and call C++ destructors on some libc
     implementations. However, if a "noexcept" function is reached, it
     may terminate the process. Other systems, such as macOS, do
     unwinding.On Windows, this function calls "_endthreadex()", which
     kills the thread without calling C++ destructors.In any case,
     there is a risk of corruption on the thread's stack.

   Obsoleto desde la versión 3.14.

void PyThread_init_thread(void)
    * Part of the Stable ABI.*

   Initialize "PyThread*" APIs. Python executes this function
   automatically, so there's little need to call it from an extension
   module.

int PyThread_set_stacksize(size_t size)
    * Part of the Stable ABI.*

   Set the stack size of the current thread to *size* bytes.

   This function returns "0" on success, "-1" if *size* is invalid, or
   "-2" if the system does not support changing the stack size. This
   function does not set exceptions.

   The caller does not need to hold an *attached thread state*.

size_t PyThread_get_stacksize(void)
    * Part of the Stable ABI.*

   Return the stack size of the current thread in bytes, or "0" if the
   system's default stack size is in use.

   The caller does not need to hold an *attached thread state*.
