初期化 (initialization)、終了処理 (finalization)、スレッド

初期化前にインタープリタを設定する方法の詳細は、Python の初期化設定 を参照してください。

Python 初期化以前

Python が埋め込まれているアプリケーションでは、他の Python/C API 関数を使う前に Py_Initialize() 関数を呼ばなければなりません。これには例外として、いくつかの関数と グローバルな設定変数 があります。

次の関数は Python の初期化の前でも安全に呼び出せます:

注釈

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().

グローバルな設定変数

Python には、様々な機能やオプションを制御するグローバルな設定のための変数があります。 デフォルトでは、これらのフラグは コマンドラインオプション で制御されます。

オプションでフラグがセットされると、フラグの値はそのオプションがセットされた回数になります。 例えば、 -b では Py_BytesWarningFlag が 1 に設定され、 -bb では Py_BytesWarningFlag が 2 に設定されます。

int Py_BytesWarningFlag

この API は後方互換性のために残されています。 代わりに PyConfig.bytes_warning を設定してください。 Python の初期化設定 を参照してください。

bytes または bytearray を str と比較した場合、または、 bytes を int と比較した場合に警告を発生させます。 2 以上の値を設定している場合は、エラーを発生させます。

-b オプションで設定します。

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

int Py_DebugFlag

この API は後方互換性のために残されています。 代わりに PyConfig.parser_debug を設定してください。 Python の初期化設定 を参照してください。

パーサーのデバッグ出力を有効にします。(専門家専用です。コンパイルオプションに依存します)。

-d オプションと PYTHONDEBUG 環境変数で設定します。

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

int Py_DontWriteBytecodeFlag

この API は後方互換性のために残されています。 代わりに PyConfig.write_bytecode を設定してください。 Python の初期化設定 を参照してください。

非ゼロに設定した場合、Python はソースモジュールのインポート時に .pyc ファイルの作成を試みません。

-B オプションと PYTHONDONTWRITEBYTECODE 環境変数で設定します。

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

int Py_FrozenFlag

この API は後方互換性のために残されています。 代わりに PyConfig.pathconfig_warnings を設定してください。 Python の初期化設定 を参照してください。

Py_GetPath() の中でモジュール検索パスを割り出しているときのエラーメッセージを抑制します。

_freeze_module プログラムと frozenmain プログラムが使用する非公開フラグです。

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

int Py_HashRandomizationFlag

この API は後方互換性のために残されています。 代わりに PyConfig.hash_seed と PyConfig.use_hash_seed を設定してください。 Python の初期化設定 を参照してください。

PYTHONHASHSEED 環境変数が空でない文字列に設定された場合に、 1 が設定されます。

フラグがゼロでない場合、 PYTHONHASHSEED 環境変数を読みシークレットハッシュシードを初期化します。

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

int Py_IgnoreEnvironmentFlag

この API は後方互換性のために残されています。 代わりに PyConfig.use_environment を設定してください。 Python の初期化設定 を参照してください。

PYTHONPATH や PYTHONHOME など、設定されているすべての PYTHON* 環境変数を無視します。

-E オプションと -I オプションで設定します。

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

int Py_InspectFlag

この API は後方互換性のために残されています。 代わりに PyConfig.inspect を設定してください。 Python の初期化設定 を参照してください。

最初の引数にスクリプトを指定した場合や -c オプションを使った場合は、sys.stdin が端末でなくても、スクリプトやコマンドの実行後に対話モードに入ります。

-i オプションと PYTHONINSPECT 環境変数で設定します。

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

int Py_InteractiveFlag

この API は後方互換性のために残されています。 代わりに PyConfig.interactive を設定してください。 Python の初期化設定 を参照してください。

-i オプションで設定します。

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

int Py_IsolatedFlag

この API は後方互換性のために残されています。 代わりに PyConfig.isolated を設定してください。 Python の初期化設定 を参照してください。

Python を隔離モードで実行します。 隔離モードでは sys.path はスクリプトのディレクトリやユーザのサイトパッケージのディレクトリを含みません。

-I オプションで設定します。

Added in version 3.4.

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

int Py_LegacyWindowsFSEncodingFlag

この API は後方互換性のために残されています。 代わりに PyPreConfig.legacy_windows_fs_encoding を設定してください。 Python の初期化設定 を参照してください。

フラグがゼロ以外の場合は、ファイルシステムエンコーディングとエラーハンドラー として、UTF-8 と surrogatepass エラーハンドラーの代わりに、mbcs と replace エラーハンドラーを使います。

PYTHONLEGACYWINDOWSFSENCODING 環境変数が空でない文字列に設定された場合に、 1 に設定されます。

より詳しくは PEP 529 を参照してください。

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

int Py_LegacyWindowsStdioFlag

この API は後方互換性のために残されています。 代わりに PyConfig.legacy_windows_stdio を設定してください。 Python の初期化設定 を参照してください。

フラグがゼロ以外の場合は、sys の標準ストリームに io._WindowsConsoleIO の代わりに io.FileIO を使います。

PYTHONLEGACYWINDOWSSTDIO 環境変数が空でない文字列に設定された場合に、 1 に設定されます。

より詳しくは PEP 528 を参照してください。

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

int Py_NoSiteFlag

この API は後方互換性のために残されています。 代わりに PyConfig.site_import を設定してください。 Python の初期化設定 を参照してください。

site モジュールの import と、そのモジュールが行なっていた site ごとの sys.path への操作を無効にします。後で site を明示的に import しても、これらの操作は実行されません (実行したい場合は、 site.main() を呼び出してください)。

-S オプションで設定します。

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

int Py_NoUserSiteDirectory

この API は後方互換性のために残されています。 代わりに PyConfig.user_site_directory を設定してください。 Python の初期化設定 を参照してください。

ユーザのサイトパッケージのディレクトリ を sys.path に追加しません。

-s オプション、 -I 、 PYTHONNOUSERSITE 環境変数で設定します。

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

int Py_OptimizeFlag

この API は後方互換性のために残されています。 代わりに PyConfig.optimization_level を設定してください。 Python の初期化設定 を参照してください。

-O オプションと PYTHONOPTIMIZE 環境変数で設定します。

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

int Py_QuietFlag

この API は後方互換性のために残されています。 代わりに PyConfig.quiet を設定してください。 Python の初期化設定 を参照してください。

インタラクティブモードでも copyright とバージョンのメッセージを表示しません。

-q オプションで設定します。

Added in version 3.2.

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

int Py_UnbufferedStdioFlag

この API は後方互換性のために残されています。 代わりに PyConfig.buffered_stdio を設定してください。 Python の初期化設定 を参照してください。

標準出力と標準エラーをバッファリングしないように強制します。

-u オプションと PYTHONUNBUFFERED 環境変数で設定します。

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

int Py_VerboseFlag

この API は後方互換性のために残されています。 代わりに PyConfig.verbose を設定してください。 Python の初期化設定 を参照してください。

モジュールが初期化されるたびにメッセージを出力し、それがどこ (ファイル名やビルトインモジュール) からロードされたのかを表示します。 値が 2 以上の場合は、モジュールを検索するときにチェックしたファイルごとにメッセージを出力します。また、終了時のモジュールクリーンアップに関する情報も提供します。

-v オプションと PYTHONVERBOSE 環境変数で設定します。

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

インタープリタの初期化と終了処理

void Py_Initialize()
次に属します: Stable ABI.

Python インタープリタを初期化します。 Python の埋め込みを行うアプリケーションでは、他のあらゆる Python/C API を使用するよりも前にこの関数を呼び出さなければなりません。いくつかの例外については Python 初期化以前 を参照してください。

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.

Python の初期化設定 をカスタマイズするには、Py_InitializeFromConfig() を使ってください。

注釈

Windows では O_TEXT から O_BINARY へコンソールモードが変更されますが、これはその C ランタイムを使っているコンソールでの Python 以外の使い勝手にも影響を及ぼします。

void Py_InitializeEx(int initsigs)
次に属します: Stable ABI.

initsigs が 1 の場合は Py_Initialize() と同じように動作します。 initsigs が 0 の場合は、シグナルハンドラーの初期化と登録を省略します。 これは、CPython をより大きなアプリケーションに組み込む場合に有用なことがあります。

Python の初期化設定 をカスタマイズするには、Py_InitializeFromConfig() を使ってください。

PyStatus Py_InitializeFromConfig(const PyConfig *config)

PyConfig による初期化 で説明するように、config の設定で Python を初期化します。

インタープリタの事前初期化、ランタイム設定構造体への値の設定、返される状態構造体の調べ方については、Python 初期化設定 を参照してください。

int Py_IsInitialized()
次に属します: Stable ABI.

Python インタプリタが初期化済みであれば真(非ゼロ)を、さもなければ偽(ゼロ)を返します。Py_FinalizeEx() を呼び出した後は、Py_Initialize() を再び呼び出すまで、この関数は偽を返します。

int Py_IsFinalizing()
次に属します: Stable ABI (バージョン 3.13 より).

メインの Python インタープリタが 終了処理中 なら真 (ゼロ以外) を返します。 それ以外の場合は偽 (ゼロ) を返します。

Added in version 3.13.

int Py_FinalizeEx()
次に属します: Stable ABI (バージョン 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(). Ideally, this frees all memory allocated by the Python interpreter. This is a no-op when called for a second time (without calling Py_Initialize() again first).

Py_Initialize() の逆の処理なので、同じスレッドで同じインタープリタがアクティブな状態で呼び出す必要があります。 つまり、メインスレッドとメインインタープリタです。 Py_RunMain() の実行中には決して呼び出してはなりません。

通常の戻り値は 0 です。 終了処理中にバッファー内のデータの書き出しでエラーがあった場合は、-1 を返します。

この関数が提供されている理由はいくつかあります。Python の埋め込みを行っているアプリケーションでは、アプリケーションを再起動することなく Python を再起動したいことがあります。また、動的ロード可能イブラリ (あるいは DLL) から Python インタプリタをロードするアプリケーションでは、DLL をアンロードする前に Python が確保したメモリを全て解放したいと考えるかもしれません。アプリケーション内で起きているメモリリークを追跡する際に、開発者は Python が確保したメモリをアプリケーションの終了前に解放させたいと思う場合もあります。

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. 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.

引数無しで 監査イベント cpython._PySys_ClearAuditHooks を送出します。

Added in version 3.6.

void Py_Finalize()
次に属します: Stable ABI.

この関数は Py_FinalizeEx() の後方互換性バージョンで、戻り値がありません。

int Py_BytesMain(int argc, char **argv)
次に属します: Stable ABI (バージョン 3.8 より).

Py_Main() と同様ですが、argv はバイト文字列の配列です。 これにより、呼び出し元のアプリケーションは、テキストのデコードを CPython ランタイムに任せられます。

Added in version 3.8.

int Py_Main(int argc, wchar_t **argv)
次に属します: Stable ABI.

標準インタープリタのメインプログラムです。 初期化から終了処理までの一連の処理に加え、環境変数とコマンドラインから設定を読み取り、コマンドライン に従って __main__ を実行する処理をまとめて行います。

より大きなアプリケーションに Python ランタイムを組み込むだけでなく、CPython の完全なコマンドラインインターフェースをサポートしたいプログラムのために提供されています。

argc と argv 引数は、C プログラムの main() 関数に渡すものに似ていますが、argv の各要素をあらかじめ Py_DecodeLocale() で wchar_t に変換する点が異なります。 引数リストの各要素が、渡された文字列とは別の文字列を指すように変更される可能性があることにも注意してください。 ただし、引数リストが指す文字列の内容は変更されません。

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

ランタイムの設定 の節で説明する CPython ランタイム設定 API を使うと、エラー処理を除いて、Py_Main はおおむね次の処理と等価です。

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

Py_RunMain();

通常、Python を組み込むアプリケーションは、Py_Initialize()、Py_InitializeEx()、Py_InitializeFromConfig() を直接呼び出す 代わりに この関数を呼び出します。 その場合、すべての設定はこのドキュメントのほかの箇所で説明されているとおりに適用されます。 先にランタイム初期化 API を呼び出した 後で この関数を呼び出す場合は、環境変数とコマンドラインのどの設定が更新されるかはバージョンに依存します。 ランタイムの最初の初期化で一度設定した値を、後から正しく変更できるかどうかが設定によって異なるためです。

int Py_RunMain(void)

設定が完了した CPython ランタイムで、メインモジュールを実行します。

コマンドラインまたは設定で指定された、コマンド (PyConfig.run_command)、スクリプト (PyConfig.run_filename)、またはモジュール (PyConfig.run_module) を実行します。 どの値も設定されていなければ、__main__ モジュールのグローバル名前空間を使って、Python の対話プロンプト (REPL) を実行します。

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.

Py_RunMain() を使って常に隔離モードで実行するようカスタマイズした Python の例は、Python の設定 を参照してください。

int PyUnstable_AtExit(PyInterpreterState *interp, void (*func)(void*), void *data)
これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。

対象のインタープリタ interp に atexit コールバックを登録します。 Py_AtExit() と似ていますが、インタープリタと、コールバックに渡すデータポインターを明示的に受け取ります。

The GIL must be held for interp.

Added in version 3.13.

プロセスワイドのパラメータ

void Py_SetProgramName(const wchar_t *name)
次に属します: Stable ABI.

この API は後方互換性のために残されています。 代わりに PyConfig.program_name を設定してください。 Python の初期化設定 を参照してください。

この関数を呼び出すなら、最初に Py_Initialize() を呼び出すよりも前に呼び出さなければなりません。この関数はインタプリタにプログラムの main() 関数に指定した argv[0] 引数の値を教えます (ワイドキャラクタに変換されます)。この引数値は、 Py_GetPath() や、以下に示すその他の関数が、インタプリタの実行可能形式から Python ランタイムライブラリへの相対パスを取得するために使われます。デフォルトの値は 'python' です。引数はゼロ終端されたワイドキャラクタ文字列で、静的な記憶領域に入っていなければならず、その内容はプログラムの実行中に変更してはなりません。 Python インタプリタ内のコードで、この記憶領域の内容を変更するものは一切ありません。

バイト文字列をデコードして wchar_t* 文字列を取得するには、Py_DecodeLocale() を使ってください。

バージョン 3.11 で非推奨.

wchar_t *Py_GetProgramName()
次に属します: Stable ABI.

Return the program name set with PyConfig.program_name, or the default. The returned string points into static storage; the caller should not modify its value.

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

Deprecated since version 3.13, will be removed in version 3.15: Get sys.executable instead.

wchar_t *Py_GetPrefix()
次に属します: 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.

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

Deprecated since version 3.13, will be removed in version 3.15: Get sys.base_prefix instead, or sys.prefix if virtual environments need to be handled.

wchar_t *Py_GetExecPrefix()
次に属します: 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.

背景: プラットフォーム依存のファイル (実行形式や共有ライブラリ) が別のディレクトリツリー内にインストールされている場合、 exec-prefix は prefix と異なります。典型的なインストール形態では、プラットフォーム非依存のファイルが /usr/local に収められる一方、プラットフォーム依存のファイルは /usr/local/plat サブツリーに収められます。

一般的に、プラットフォームとは、ハードウェアとソフトウェアファミリの組み合わせを指します。例えば、Solaris 2.x を動作させている Sparc マシンは全て同じプラットフォームであるとみなしますが、Solaris 2.x を動作させている Intel マシンは違うプラットフォームになりますし、同じ Intel マシンでも Linux を動作させているならまた別のプラットフォームです。一般的には、同じオペレーティングシステムでも、メジャーリビジョンの違うものは異なるプラットフォームです。非 Unix のオペレーティングシステムの場合は話はまた別です; 非 Unix のシステムでは、インストール方法はとても異なっていて、prefix や exec-prefix には意味がなく、空文字列が設定されています。コンパイル済みの Python バイトコードはプラットフォームに依存しないので注意してください (ただし、どのバージョンの Python でコンパイルされたかには依存します!)。

システム管理者は、 mount や automount プログラムを使って、各プラットフォーム用の /usr/local/plat を異なったファイルシステムに置き、プラットフォーム間で /usr/local を共有するための設定方法を知っているでしょう。

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

Deprecated since version 3.13, will be removed in version 3.15: Get sys.base_exec_prefix instead, or sys.exec_prefix if virtual environments need to be handled.

wchar_t *Py_GetProgramFullPath()
次に属します: Stable ABI.

Return the full program name of the Python executable; this is computed as a side-effect of deriving the default module search path from the program name (set by PyConfig.program_name). The returned string points into static storage; the caller should not modify its value. The value is available to Python code as sys.executable.

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

Deprecated since version 3.13, will be removed in version 3.15: Get sys.executable instead.

wchar_t *Py_GetPath()
次に属します: Stable ABI.

Return the default module search path; this is computed from the program name (set by PyConfig.program_name) and some environment variables. The returned string consists of a series of directory names separated by a platform dependent delimiter character. The delimiter character is ':' on Unix and macOS, ';' on Windows. The returned string points into static storage; the caller should not modify its value. The list sys.path is initialized with this value on interpreter startup; it can be (and usually is) modified later to change the search path for loading modules.

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

Deprecated since version 3.13, will be removed in version 3.15: Get sys.path instead.

const char *Py_GetVersion()
次に属します: Stable ABI.

Python インタプリタのバージョンを返します。バージョンは、次のような形式の文字列です

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

第一ワード (最初のスペース文字まで) は、現在の Python のバージョンです; 最初の文字は、ピリオドで区切られたメジャーバージョンとマイナーバージョンです。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.version として利用できます。

Py_Version 定数も参照してください。

const char *Py_GetPlatform()
次に属します: Stable ABI.

現在のプラットフォームのプラットフォーム識別文字列を返します。Unixでは、オペレーティングシステムの "公式の" 名前を小文字に変換し、後ろにメジャーリビジョン番号を付けた構成になっています。例えば Solaris 2.x は、SunOS 5.x, としても知られていますが、'sunos5' になります。macOS では 'darwin' です。Windows では 'win' です。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.platform として利用できます。

const char *Py_GetCopyright()
次に属します: Stable ABI.

現在の Python バージョンに対する公式の著作権表示文字列を返します。例えば

'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'

関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.copyright として利用できます。

const char *Py_GetCompiler()
次に属します: Stable ABI.

現在使っているバージョンの Python をビルドする際に用いたコンパイラを示す文字列を、角括弧で囲った文字列を返します。例えば:

"[GCC 2.7.2.2]"

関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.version の一部として取り出せます。

const char *Py_GetBuildInfo()
次に属します: Stable ABI.

現在使っている Python インタプリタインスタンスの、シーケンス番号とビルド日時に関する情報を返します。例えば

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

関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.version の一部として取り出せます。

void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
次に属します: Stable ABI.

この API は後方互換性のために残されています。 代わりに PyConfig.argv と PyConfig.parse_argv と PyConfig.safe_path を設定してください。 Python の初期化設定 を参照してください。

argc および argv に基づいて sys.argv を設定します。これらの引数はプログラムの main() に渡した引数に似ていますが、最初の要素が Python インタプリタの宿主となっている実行形式の名前ではなく、実行されるスクリプト名を参照しなければならない点が違います。実行するスクリプトがない場合、 argv の最初の要素は空文字列にしてもかまいません。この関数が sys.argv の初期化に失敗した場合、致命的エラーを Py_FatalError() で知らせます。

updatepath が 0 の場合、ここまでの動作がこの関数がすることの全てです。 updatepath が 0 でない場合、この関数は sys.path を以下のアルゴリズムに基づいて修正します:

  • 存在するスクリプトの名前が argv[0] に渡された場合、そのスクリプトがある場所の絶対パスを sys.path の先頭に追加します。

  • それ以外の場合 (argc が 0 だったり、 argv[0] が存在するファイル名を指していない場合)、 sys.path の先頭に空の文字列を追加します。 これは現在の作業ディレクトリ (".") を先頭に追加するのと同じです。

バイト文字列をデコードして wchar_t* 文字列を取得するには、Py_DecodeLocale() を使ってください。

Python の初期化設定 の PyConfig.orig_argv と PyConfig.argv メンバーも参照してください。

注釈

単一のスクリプトを実行する以外の目的で Python インタープリタを組み込むアプリケーションでは、updatepath に 0 を渡し、必要なら sys.path を自分で更新することを推奨します。 CVE 2008-5983 を参照してください。

3.1.3 より前のバージョンでは、 PySys_SetArgv() の呼び出しが完了した後に sys.path の先頭の要素を取り出すことで、同じ効果が得られます。例えばこのように使います:

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

Added in version 3.1.3.

バージョン 3.11 で非推奨.

void PySys_SetArgv(int argc, wchar_t **argv)
次に属します: Stable ABI.

この API は後方互換性のために残されています。 代わりに PyConfig.argv と PyConfig.parse_argv を設定してください。 Python の初期化設定 を参照してください。

この関数は、 python インタプリタが -I オプション付きで実行されている場合を除き PySys_SetArgvEx() の updatepath に 1 を設定したのと同じように動作します。

バイト文字列をデコードして wchar_t* 文字列を取得するには、Py_DecodeLocale() を使ってください。

Python の初期化設定 の PyConfig.orig_argv と PyConfig.argv メンバーも参照してください。

バージョン 3.4 で変更: updatepath の値は -I オプションに依存します。

バージョン 3.11 で非推奨.

void Py_SetPythonHome(const wchar_t *home)
次に属します: Stable ABI.

この API は後方互換性のために残されています。 代わりに PyConfig.home を設定してください。 Python の初期化設定 を参照してください。

Python の標準ライブラリがある、デフォルトの "home" ディレクトリを設定します。引数の文字列の意味については PYTHONHOME を参照してください。

引数は静的なストレージに置かれてプログラム実行中に書き換えられないようなゼロ終端の文字列であるべきです。Python インタプリタはこのストレージの内容を変更しません。

バイト文字列をデコードして wchar_t* 文字列を取得するには、Py_DecodeLocale() を使ってください。

バージョン 3.11 で非推奨.

wchar_t *Py_GetPythonHome()
次に属します: Stable ABI.

Return the default "home", that is, the value set by PyConfig.home, or the value of the PYTHONHOME environment variable if it is set.

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

Deprecated since version 3.13, will be removed in version 3.15: Get PyConfig.home or PYTHONHOME environment variable instead.

スレッド状態 (thread state) とグローバルインタプリタロック (global interpreter lock)

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.

このため、 GIL を獲得したスレッドだけが Python オブジェクトを操作したり、 Python/C API 関数を呼び出したりできるというルールがあります。並行処理をエミュレートするために、インタプリタは定期的にロックを解放したり獲得したりします。 (sys.setswitchinterval() を参照) このロックはブロックが起こりうる I/O 操作の付近でも解放・獲得され、 I/O を要求するスレッドが I/O 操作の完了を待つ間、他のスレッドが動作できるようにしています。

The Python interpreter keeps some thread-specific bookkeeping information inside a data structure called PyThreadState. There's also one global variable pointing to the current PyThreadState: it can be retrieved using PyThreadState_Get().

Releasing the GIL from extension code

Most extension code manipulating the GIL has the following simple structure:

Save the thread state in a local variable.
Release the global interpreter lock.
... Do some blocking I/O operation ...
Reacquire the global interpreter lock.
Restore the thread state from the local variable.

この構造は非常に一般的なので、作業を単純にするために2つのマクロが用意されています:

Py_BEGIN_ALLOW_THREADS
... ブロッキング I/O 操作を行う ...
Py_END_ALLOW_THREADS

Py_BEGIN_ALLOW_THREADS マクロは新たなブロックを開始し、隠しローカル変数を宣言します; Py_END_ALLOW_THREADS はブロックを閉じます。

上のブロックは次のコードに展開されます:

PyThreadState *_save;

_save = PyEval_SaveThread();
... ブロッキング I/O 操作を行う ...
PyEval_RestoreThread(_save);

Here is how these functions work: the global interpreter lock is used to protect the pointer to the current thread state. When releasing the lock and saving the thread state, the current thread state pointer must be retrieved before the lock is released (since another thread could immediately acquire the lock and store its own thread state in the global variable). Conversely, when acquiring the lock and restoring the thread state, the lock must be acquired before storing the thread state pointer.

注釈

Calling system I/O functions is the most common use case for releasing the GIL, 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 release the GIL when compressing or hashing data.

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, nor is there a thread state structure for them.

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 a thread state data structure, then acquiring the GIL, and finally storing their thread state pointer, before you can start using the Python/C API. When you are done, you should reset the thread state pointer, release the GIL, and finally free the thread state data structure.

PyGILState_Ensure() と PyGILState_Release() はこの処理を自動的に行います。 Cのスレッドから Python を呼び出す典型的な方法は以下のとおりです:

PyGILState_STATE gstate;
gstate = PyGILState_Ensure();

/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */

/* Release the thread. No Python API allowed beyond this point. */
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.

fork() に関する注意

スレッドに関するもう 1 つの重要な注意点は、C の fork() 呼び出し時の動作です。 fork() を備えるほとんどのシステムでは、プロセスを fork した後には、fork を呼び出したスレッドだけが存在します。 これは、ロックの扱い方と CPython ランタイムに保存されたすべての状態の両方に、具体的な影響を及ぼします。

「現在の」スレッドだけが残るため、ほかのスレッドが保持していたロックは解放されなくなります。 Python は os.fork() で、内部で使うロックを fork の前に取得し、後で解放することで対処します。 さらに、子プロセスの Lock オブジェクト をすべてリセットします。 Python の拡張や組み込みでは、fork 前の取得や fork 後のリセットが必要な、Python 以外の追加のロックを Python に知らせる方法はありません。 同じ処理を行うには、pthread_atfork() などの OS の機能を使う必要があります。 また、Python の拡張や組み込みで os.fork() を経由せずに fork() を直接呼び出し、その後 Python に戻るか Python を呼び出すと、デッドロックが起こる可能性があります。 Python 内部のロックを保持していたスレッドが、fork 後には存在しなくなるためです。 PyOS_AfterFork_Child() は必要なロックのリセットを試みますが、常にできるとは限りません。

ほかのスレッドがすべて消えるため、それらに対応する CPython ランタイムの状態も適切に後始末する必要があります。 os.fork() はこの処理を行います。 具体的には、現在のインタープリタに属するほかのすべての PyThreadState オブジェクトと、ほかのすべての PyInterpreterState オブジェクトの終了処理を行います。 このことと メインインタープリタ の特殊な性質のため、fork() は、CPython のグローバルなランタイムを最初に初期化した、そのインタープリタの「メイン」スレッドでのみ呼び出すべきです。 直後に exec() を呼び出す場合だけは例外です。

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 acquire the GIL during finalization, either explicitly via PyGILState_Ensure(), Py_END_ALLOW_THREADS, PyEval_AcquireThread(), or PyEval_AcquireLock(), or implicitly when the interpreter attempts to reacquire it after having yielded it, 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.7 and earlier. The CPython runtime GIL acquiring C APIs have never had any error reporting or handling expectations at GIL acquisition 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

C拡張を書いたりPythonインタプリタを埋め込むときに最も一般的に使われる型や関数は次のとおりです:

type PyInterpreterState
次に属します: Limited API (不透明な構造体として).

このデータ構造体は、協調動作する多数のスレッド間で共有されている状態を表現します。同じインタプリタに属するスレッドはモジュール管理情報やその他いくつかの内部的な情報を共有しています。この構造体には公開 (public) のメンバはありません。

異なるインタプリタに属するスレッド間では、利用可能なメモリ、開かれているファイルデスクリプタなどといったプロセス状態を除いて、初期状態では何も共有されていません。GILもまた、スレッドがどのインタプリタに属しているかに関わらずすべてのスレッドで共有されています。

バージョン 3.12 で変更: PEP 684 introduced the possibility of a per-interpreter GIL. See Py_NewInterpreterFromConfig().

type PyThreadState
次に属します: Limited API (不透明な構造体として).

このデータ構造は、1 つのスレッドの状態を表します。 公開されているデータメンバーは次のものだけです。

PyInterpreterState *interp

このスレッドのインタープリタ状態。

void PyEval_InitThreads()
次に属します: Stable ABI.

何も行わない非推奨の関数です。

Python 3.6 以前では、GIL が存在しなければ作成していました。

バージョン 3.9 で変更: この関数は何も行わなくなりました。

バージョン 3.7 で変更: この関数は Py_Initialize() から呼び出されるようになり、わざわざ呼び出す必要はもう無くなりました。

バージョン 3.2 で変更: この関数は Py_Initialize() より前に呼び出すことができなくなりました。

バージョン 3.9 で非推奨.

PyThreadState *PyEval_SaveThread()
次に属します: Stable ABI.

Release the global interpreter lock (if it has been created) and reset the thread state to NULL, returning the previous thread state (which is not NULL). If the lock has been created, the current thread must have acquired it.

void PyEval_RestoreThread(PyThreadState *tstate)
次に属します: Stable ABI.

Acquire the global interpreter lock (if it has been created) and set the thread state to tstate, which must not be NULL. If the lock has been created, the current thread must not have acquired it, otherwise deadlock ensues.

注釈

ランタイムの終了処理中にスレッドからこの関数を呼び出すと、そのスレッドはプログラムが終了するまで停止したままになります。 これは Python で作成したスレッドでなくても同じです。 詳しくは Cautions regarding runtime finalization を参照してください。

バージョン 3.13.8 で変更: インタープリタの終了処理中に呼び出された場合、現在のスレッドを終了させる代わりに、停止したままにするようになりました。

PyThreadState *PyThreadState_Get()
次に属します: Stable ABI.

Return the current thread state. The global interpreter lock must be held. When the current thread state is NULL, this issues a fatal error (so that the caller needn't check for NULL).

PyThreadState_GetUnchecked() も参照してください。

PyThreadState *PyThreadState_GetUnchecked()

PyThreadState_Get() と同様ですが、スレッド状態が NULL でも致命的エラーでプロセスを終了させません。 結果が NULL かどうかは、呼び出し元が調べる必要があります。

Added in version 3.13: Python 3.5 から 3.12 では、この関数は非公開で、_PyThreadState_UncheckedGet() という名前でした。

PyThreadState *PyThreadState_Swap(PyThreadState *tstate)
次に属します: Stable ABI.

Swap the current thread state with the thread state given by the argument tstate, which may be NULL.

The GIL does not need to be held, but will be held upon returning if tstate is non-NULL.

以下の関数はスレッドローカルストレージを利用していて、サブインタプリタとの互換性がありません:

type PyGILState_STATE
次に属します: 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()
次に属します: 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 global interpreter lock. 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 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, the current thread will hold the GIL and be able to call arbitrary Python code. Failure is a fatal error.

注釈

ランタイムの終了処理中にスレッドからこの関数を呼び出すと、そのスレッドはプログラムが終了するまで停止したままになります。 これは Python で作成したスレッドでなくても同じです。 詳しくは Cautions regarding runtime finalization を参照してください。

バージョン 3.13.8 で変更: インタープリタの終了処理中に呼び出された場合、現在のスレッドを終了させる代わりに、停止したままにするようになりました。

void PyGILState_Release(PyGILState_STATE)
次に属します: Stable ABI.

獲得したすべてのリソースを解放します。この関数を呼び出すと、Pythonの状態は対応する PyGILState_Ensure() を呼び出す前と同じとなります (通常、この状態は呼び出し元でははわかりませんので、GILState APIを利用するようにしてください)。

PyGILState_Ensure() を呼び出す場合は、必ず同一スレッド内で対応する PyGILState_Release() を呼び出してください。

PyThreadState *PyGILState_GetThisThreadState()
次に属します: Stable ABI.

Get the current 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.

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 Python thread state initialized and currently is holding the GIL 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.

Added in version 3.4.

以下のマクロは、通常末尾にセミコロンを付けずに使います; Python ソース配布物内の使用例を見てください。

Py_BEGIN_ALLOW_THREADS
次に属します: Stable ABI.

このマクロを展開すると { PyThreadState *_save; _save = PyEval_SaveThread(); になります。マクロに開き波括弧が入っていることに注意してください; この波括弧は後で Py_END_ALLOW_THREADS マクロと対応させなければなりません。マクロについての詳しい議論は上記を参照してください。

Py_END_ALLOW_THREADS
次に属します: Stable ABI.

このマクロを展開すると PyEval_RestoreThread(_save); } になります。 閉じ波括弧を含むため、事前の Py_BEGIN_ALLOW_THREADS マクロと対応させなければなりません。 このマクロについては上の説明を参照してください。

Py_BLOCK_THREADS
次に属します: Stable ABI.

このマクロを展開すると PyEval_RestoreThread(_save); になります: 閉じ波括弧のない Py_END_ALLOW_THREADS と同じです。

Py_UNBLOCK_THREADS
次に属します: Stable ABI.

このマクロを展開すると _save = PyEval_SaveThread(); になります: 開き波括弧のない Py_BEGIN_ALLOW_THREADS と同じです。

低レベルAPI

次の全ての関数は Py_Initialize() の後に呼び出さなければなりません。

バージョン 3.7 で変更: Py_Initialize() now initializes the GIL.

PyInterpreterState *PyInterpreterState_New()
次に属します: Stable ABI.

Create a new interpreter state object. The global interpreter lock need not be held, but may be held if it is necessary to serialize calls to this function.

引数無しで 監査イベント cpython.PyInterpreterState_New を送出します。

void PyInterpreterState_Clear(PyInterpreterState *interp)
次に属します: Stable ABI.

Reset all information in an interpreter state object. The global interpreter lock must be held.

引数無しで 監査イベント cpython.PyInterpreterState_Clear を送出します。

void PyInterpreterState_Delete(PyInterpreterState *interp)
次に属します: Stable ABI.

Destroy an interpreter state object. The global interpreter lock need not be held. The interpreter state must have been reset with a previous call to PyInterpreterState_Clear().

PyThreadState *PyThreadState_New(PyInterpreterState *interp)
次に属します: Stable ABI.

Create a new thread state object belonging to the given interpreter object. The global interpreter lock need not be held, but may be held if it is necessary to serialize calls to this function.

void PyThreadState_Clear(PyThreadState *tstate)
次に属します: Stable ABI.

Reset all information in a thread state object. The global interpreter lock must be held.

バージョン 3.9 で変更: This function now calls the PyThreadState.on_delete callback. Previously, that happened in PyThreadState_Delete().

バージョン 3.13 で変更: The PyThreadState.on_delete callback was removed.

void PyThreadState_Delete(PyThreadState *tstate)
次に属します: Stable ABI.

Destroy a thread state object. The global interpreter lock need not be held. The thread state must have been reset with a previous call to PyThreadState_Clear().

void PyThreadState_DeleteCurrent(void)

Destroy the current thread state and release the global interpreter lock. Like PyThreadState_Delete(), the global interpreter lock must be held. The thread state must have been reset with a previous call to PyThreadState_Clear().

PyFrameObject *PyThreadState_GetFrame(PyThreadState *tstate)
次に属します: Stable ABI (バージョン 3.10 より).

Python のスレッド状態 tstate の現在のフレームを取得します。

強参照 を返します。 現在実行中のフレームがなければ NULL を返します。

PyEval_GetFrame() も参照してください。

tstate must not be NULL.

Added in version 3.9.

uint64_t PyThreadState_GetID(PyThreadState *tstate)
次に属します: Stable ABI (バージョン 3.10 より).

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

tstate must not be NULL.

Added in version 3.9.

PyInterpreterState *PyThreadState_GetInterpreter(PyThreadState *tstate)
次に属します: Stable ABI (バージョン 3.10 より).

Python のスレッド状態 tstate のインタープリタを取得します。

tstate must not be NULL.

Added in version 3.9.

void PyThreadState_EnterTracing(PyThreadState *tstate)

Python のスレッド状態 tstate でのトレースとプロファイリングを一時停止します。

再開するには PyThreadState_LeaveTracing() を使います。

Added in version 3.11.

void PyThreadState_LeaveTracing(PyThreadState *tstate)

PyThreadState_EnterTracing() によって一時停止した、Python のスレッド状態 tstate でのトレースとプロファイリングを再開します。

PyEval_SetTrace() と PyEval_SetProfile() も参照してください。

Added in version 3.11.

PyInterpreterState *PyInterpreterState_Get(void)
次に属します: Stable ABI (バージョン 3.9 より).

現在のインタープリタを取得します。

Issue a fatal error if there is no current Python thread state or no current interpreter. It cannot return NULL.

The caller must hold the GIL.

Added in version 3.9.

int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
次に属します: Stable ABI (バージョン 3.7 より).

インタプリタの一意な ID を返します。 処理中に何かエラーが起きたら、 -1 が返され、エラーがセットされます。

The caller must hold the GIL.

Added in version 3.7.

PyObject *PyInterpreterState_GetDict(PyInterpreterState *interp)
戻り値: 借用参照。 次に属します: Stable ABI (バージョン 3.8 より).

インタプリタ固有のデータを保持している辞書を返します。 この関数が NULL を返した場合は、ここまでで例外は送出されておらず、呼び出し側はインタプリタ固有の辞書は利用できないと考えなければなりません。

これは PyModule_GetState() の代わりにはなりません。 拡張がインタープリタ固有の状態情報を保存するには、そちらを使うべきです。

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

Added in version 3.8.

PyObject *PyUnstable_InterpreterState_GetMainModule(PyInterpreterState *interp)
これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。

Return a strong reference to the __main__ module object for the given interpreter.

The caller must hold the GIL.

Added in version 3.13.

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

フレーム評価関数の型。

throwflag 引数は、ジェネレーターの throw() メソッドが使います。 ゼロ以外の場合は、現在の例外を処理します。

バージョン 3.9 で変更: tstate 引数を受け取るようになりました。

バージョン 3.11 で変更: frame 引数が PyFrameObject* から _PyInterpreterFrame* に変わりました。

_PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)

フレーム評価関数を取得します。

PEP 523 「Adding a frame evaluation API to CPython」を参照してください。

Added in version 3.9.

void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)

フレーム評価関数を設定します。

PEP 523 「Adding a frame evaluation API to CPython」を参照してください。

Added in version 3.9.

PyObject *PyThreadState_GetDict()
戻り値: 借用参照。 次に属します: 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 current thread state is available. If this function returns NULL, no exception has been raised and the caller should assume no current thread state is available.

int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
次に属します: 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 the GIL held. 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.

バージョン 3.7 で変更: id 引数の型が long から unsigned long へ変更されました。

void PyEval_AcquireThread(PyThreadState *tstate)
次に属します: Stable ABI.

Acquire the global interpreter lock and set the current thread state to tstate, which must not be NULL. The lock must have been created earlier. If this thread already has the lock, deadlock ensues.

注釈

ランタイムの終了処理中にスレッドからこの関数を呼び出すと、そのスレッドはプログラムが終了するまで停止したままになります。 これは Python で作成したスレッドでなくても同じです。 詳しくは Cautions regarding runtime finalization を参照してください。

バージョン 3.8 で変更: PyEval_RestoreThread()、Py_END_ALLOW_THREADS()、PyGILState_Ensure() と動作を揃え、インタープリタの終了処理中に呼び出された場合は、現在のスレッドを終了させるようになりました。

バージョン 3.13.8 で変更: インタープリタの終了処理中に呼び出された場合、現在のスレッドを終了させる代わりに、停止したままにするようになりました。

PyEval_RestoreThread() はいつでも (スレッドが初期化されたいないときでも) 利用可能な高レベル関数です。

void PyEval_ReleaseThread(PyThreadState *tstate)
次に属します: Stable ABI.

Reset the current thread state to NULL and release the global interpreter lock. The lock must have been created earlier and must be held by the current thread. The tstate argument, which must not be NULL, is only used to check that it represents the current thread state --- if it isn't, a fatal error is reported.

PyEval_SaveThread() はより高レベルな関数で常に (スレッドが初期化されていないときでも) 利用できます。

サブインタプリタサポート

ほとんどの場合は埋め込む Python インタプリタは1つだけですが、いくつかの場合に同一プロセス内、あるいは同一スレッド内で、複数の独立したインタプリタを作成する必要があります。 これを可能にするのがサブインタプリタです。

「メイン」インタープリタは、ランタイムの初期化時に最初に作成されるインタープリタです。 通常、プロセス内の Python インタープリタはこれだけです。 サブインタープリタとは異なり、メインインタープリタはシグナル処理などの、プロセス全体に関わる固有の役割を担います。 ランタイムの初期化中の実行も担い、通常はランタイムの終了処理中にもアクティブなインタープリタです。 PyInterpreterState_Main() は、その状態へのポインターを返します。

サブインタプリタを切り替えが PyThreadState_Swap() 関数でできます。 次の関数を使ってサブインタプリタの作成と削除が行えます:

type PyInterpreterConfig

サブインタープリタの設定に使うパラメーターの大部分を含む構造体です。 値は Py_NewInterpreterFromConfig() でのみ使用され、ランタイムによって変更されることはありません。

Added in version 3.12.

構造体フィールド:

int use_main_obmalloc

0 の場合、サブインタープリタは独自の「オブジェクト」アロケーターの状態を使います。 それ以外の場合は、メインインタープリタの状態を共有して使います。

0 の場合、check_multi_interp_extensions は 1 (ゼロ以外) でなければなりません。 1 の場合、gil は PyInterpreterConfig_OWN_GIL であってはなりません。

int allow_fork

0 の場合、このサブインタープリタが現在アクティブなスレッドでは、ランタイムはプロセスの fork を許可しません。 それ以外の場合、fork に制限はありません。

fork を許可しなくても、subprocess モジュールは動作します。

int allow_exec

0 の場合、このサブインタープリタが現在アクティブなスレッドでは、ランタイムは exec (os.execv() など) による現在のプロセスの置き換えを許可しません。 それ以外の場合、exec に制限はありません。

exec を許可しなくても、subprocess モジュールは動作します。

int allow_threads

0 の場合、このサブインタープリタの threading モジュールはスレッドを作成しません。 それ以外の場合は、スレッドの作成が許可されます。

int allow_daemon_threads

0 の場合、このサブインタープリタの threading モジュールはデーモンスレッドを作成しません。 それ以外の場合は、allow_threads がゼロでない限り、デーモンスレッドの作成が許可されます。

int check_multi_interp_extensions

0 の場合、このサブインタープリタが現在アクティブなスレッドでは、従来の単相初期化モジュールを含め、すべての拡張モジュールをインポートできます。 それ以外の場合は、多相初期化を使う拡張モジュールのみインポートできます (PEP 489 を参照)。 Py_mod_multiple_interpreters も参照してください。

use_main_obmalloc が 0 の場合は、1 (ゼロ以外) でなければなりません。

int gil

サブインタープリタの GIL の動作を指定します。 次のいずれかの値を取ります。

PyInterpreterConfig_DEFAULT_GIL

デフォルトの選択 (PyInterpreterConfig_SHARED_GIL) を使います。

PyInterpreterConfig_SHARED_GIL

メインインタープリタの GIL を共有して使います。

PyInterpreterConfig_OWN_GIL

サブインタープリタ独自の GIL を使います。

PyInterpreterConfig_OWN_GIL の場合、PyInterpreterConfig.use_main_obmalloc は 0 でなければなりません。

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

新しいサブインタプリタ (sub-interpreter) を生成します。サブインタプリタとは、(ほぼ完全に) 個別に分割された Python コードの実行環境です。特に、新しいサブインタプリタは、 import されるモジュール全てについて個別のバージョンを持ち、これには基盤となるモジュール builtins, __main__ および sys も含まれます。ロード済みのモジュールからなるテーブル (sys.modules) およびモジュール検索パス (sys.path) もサブインタプリタ毎に別個のものになります。新たなサブインタプリタ環境には sys.argv 変数がありません。また、サブインタプリタは新たな標準 I/O ストリーム sys.stdin, sys.stdout, sys.stderr を持ちます (とはいえ、これらのストリームは根底にある同じファイル記述子を参照しています)。

config は、インタープリタの初期化に使うオプションを指定します。

Upon success, tstate_p will be set to the first thread state created in the new sub-interpreter. This thread state is made in the current thread state. 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 current thread state and there may not be a current thread state.

Like all other Python/C API functions, the global interpreter lock must be held before calling this function and is still held when it returns. Likewise a current thread state must be set on entry. On success, the returned thread state will be set as current. If the sub-interpreter is created with its own GIL then the GIL of the calling interpreter will be released. When the function returns, the new interpreter's GIL will be held by the current thread and the previously interpreter's GIL will remain released here.

Added in version 3.12.

サブインタープリタは、一部の機能を制限して互いに隔離したときに、最も効果を発揮します。

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);
}

設定は短時間だけ使われ、変更されることはありません。 初期化中に、設定の値が PyInterpreterState の各種の値に変換されます。 設定の読み取り専用のコピーが、PyInterpreterState 内部に保存される場合もあります。

拡張モジュールは、インタープリタ間 (サブインタープリタを含む) で次のように共有されます。

  • PyModule_FromDefAndSpec() などの多相初期化を使うモジュールでは、インタープリタごとに別のモジュールオブジェクトを作成して初期化します。 これらのモジュールオブジェクトが共有するのは、C レベルの静的変数とグローバル変数だけです。

  • For modules using single-phase initialization, e.g. PyModule_Create(), the first time a particular extension is imported, it is initialized normally, and a (shallow) copy of its module's dictionary is squirreled away. When the same extension is imported by another (sub-)interpreter, a new module is initialized and filled with the contents of this copy; the extension's init function is not called. Objects in the module's dictionary thus end up shared across (sub-)interpreters, which might cause unwanted behavior (see Bugs and caveats below).

    Py_FinalizeEx() と Py_Initialize() を呼び出してインタープリタを完全に再初期化した後で、拡張をインポートする場合とは異なります。 その場合は、拡張の initmodule 関数が再び呼び出され ます。 多相初期化の場合と同様に、これらのモジュール間で共有されるのは、C レベルの静的変数とグローバル変数だけです。

PyThreadState *Py_NewInterpreter(void)
次に属します: Stable ABI.

新しいサブインタープリタを作成します。 基本的には、従来の動作を維持する設定で Py_NewInterpreterFromConfig() を呼び出すラッパーです。 作成されるサブインタープリタは隔離されておらず、メインインタープリタの GIL を共有し、fork/exec、デーモンスレッド、単相初期化モジュールを許可します。

void Py_EndInterpreter(PyThreadState *tstate)
次に属します: Stable ABI.

Destroy the (sub-)interpreter represented by the given thread state. The given thread state must be the current thread state. See the discussion of thread states below. When the call returns, the current thread state is NULL. All thread states associated with this interpreter are destroyed. The global interpreter lock used by the target interpreter must be held before calling this function. No GIL is held when it returns.

Py_FinalizeEx() は、その時点で明示的に破棄されていないサブインタープリタをすべて破棄します。

A Per-Interpreter GIL

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.)

隔離されたインタープリタを使うには、隔離を維持するよう注意しなければなりません。 特に、スレッドセーフである保証なしにオブジェクトや可変の状態を共有してはいけません。 参照カウントがあるため、None や (1, 5) のように、それ以外の点では不変なオブジェクトであっても、通常は共有できません。 単純ですが効率の劣る回避策として、ある状態やオブジェクトを使うすべての操作をグローバルなロックで保護する方法があります。 また、整数や文字列のように実質的に不変なオブジェクトは、不死 にすることで、参照カウントがあっても安全にできます。 実際に、組み込みのシングルトン、小さい整数、その他多くの組み込みオブジェクトにこの方法が使われています。

隔離を維持すれば、フリースレッド化に伴う複雑さなしに、複数のコアを使った計算を行えます。 隔離を維持できなければ、競合状態やデバッグの難しいクラッシュなど、フリースレッド化のあらゆる問題にさらされます。

Aside from that, one of the main challenges of using multiple isolated interpreters is how to communicate between them safely (not break isolation) and efficiently. The runtime and stdlib do not provide any standard approach to this yet. A future stdlib module would help mitigate the effort of preserving isolation and expose effective tools for communicating (and sharing) data between interpreters.

Added in version 3.12.

バグと注意事項

Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isn't perfect --- for example, using low-level file operations like os.close() they can (accidentally or maliciously) affect each other's open files. Because of the way extensions are shared between (sub-)interpreters, some extensions may not work properly; this is especially likely when using single-phase initialization or (static) global variables. It is possible to insert objects created in one sub-interpreter into a namespace of another (sub-)interpreter; this should be avoided if possible.

サブインタープリタ間で、ユーザー定義の関数、メソッド、インスタンス、クラスを共有しないよう、特に注意するべきです。 それらが実行するインポート操作によって、誤ったインタープリタのロード済みモジュールの辞書に影響する可能性があるためです。 これらのオブジェクトにたどり着けるオブジェクトの共有を避けることも、同様に重要です。

サブインタプリタを PyGILState_* API と組み合わせるのが難しいことにも注意してください。これらのAPIはPythonのスレッド状態とOSレベルスレッドが1対1で対応していることを前提にしていて、サブインタプリタが存在するとその前提が崩れるからです。対応する PyGILState_Ensure() と PyGILState_Release() の呼び出しのペアの間では、サブインタプリタの切り替えを行わないことを強く推奨します。さらに、(ctypes のような)これらのAPIを使ってPythonの外で作られたスレッドから Pythonコードを実行している拡張モジュールはサブインタプリタを使うと壊れる可能性があります。

非同期通知

インタプリタのメインスレッドに非同期な通知を行うために提供されている仕組みです。これらの通知は関数ポインタと void ポインタ引数という形態を取ります。

int Py_AddPendingCall(int (*func)(void*), void *arg)
次に属します: Stable ABI.

インタプリタのメインスレッドから関数が呼び出される予定を組みます。成功すると 0 が返り、func はメインスレッドの呼び出しキューに詰められます。失敗すると、例外をセットせずに -1 が返ります。

無事にキューに詰められると、func は いつかは必ず インタプリタのメインスレッドから、arg を引数として呼び出されます。この関数は、通常の実行中の Python コードに対して非同期に呼び出されますが、次の両方の条件に合致したときに呼び出されます:

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 global interpreter lock is released.

This function doesn't need a current thread state to run, and it doesn't need the global interpreter lock.

To call this function in a subinterpreter, the caller must hold the GIL. Otherwise, the function func can be scheduled to be called from the wrong interpreter.

警告

これは、非常に特別な場合にのみ役立つ、低レベルな関数です。 func が可能な限り早く呼び出される保証はありません。メインスレッドがシステムコールを実行するのに忙しい場合は、 func はシステムコールが返ってくるまで呼び出されないでしょう。この関数は一般的には、任意の C スレッドから Python コードを呼び出すのには 向きません 。これの代わりに、 PyGILState API を使用してください。

Added in version 3.1.

バージョン 3.9 で変更: サブインタープリタでこの関数を呼び出すと、func はメインインタープリタではなく、そのサブインタープリタで呼び出されるようになりました。 サブインタープリタごとに、呼び出しを予定した関数のリストを持つようになりました。

バージョン 3.12 で変更: This function now always schedules func to be run in the main interpreter.

int Py_MakePendingCalls(void)
次に属します: 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 the GIL.

Added in version 3.1.

バージョン 3.12 で変更: This function only runs pending calls in the main interpreter.

プロファイルとトレース (profiling and tracing)

Python インタプリタは、プロファイル: 分析 (profile) や実行のトレース: 追跡 (trace) といった機能を組み込むために低水準のサポートを提供しています。このサポートは、プロファイルやデバッグ、適用範囲分析 (coverage analysis) ツールなどに使われます。

この C インターフェースは、プロファイルやトレース作業時に、Python レベルの呼び出し可能オブジェクトが呼び出されることによるオーバヘッドを避け、直接 C 関数呼び出しが行えるようにしています。プロファイルやトレース機能の本質的な特性は変わっていません; インターフェースではトレース関数をスレッドごとにインストールでき、トレース関数に報告される基本イベント (basic event) は以前のバージョンにおいて Python レベルのトレース関数で報告されていたものと同じです。

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

PyEval_SetProfile() と PyEval_SetTrace() で登録するトレース関数の型です。 第 1 引数は登録関数に obj として渡したオブジェクト、frame はイベントの対象のフレームオブジェクトです。 what は定数 PyTrace_CALL、PyTrace_EXCEPTION、PyTrace_LINE、PyTrace_RETURN、PyTrace_C_CALL、PyTrace_C_EXCEPTION、PyTrace_C_RETURN、PyTrace_OPCODE のいずれかで、arg は what の値によって異なります。

what の値

arg の意味

PyTrace_CALL

常に Py_None 。

PyTrace_EXCEPTION

sys.exc_info() の返す例外情報です。

PyTrace_LINE

常に Py_None 。

PyTrace_RETURN

呼び出し側に返される予定の値か、例外によって関数を抜ける場合は NULL です。

PyTrace_C_CALL

呼び出される関数オブジェクト。

PyTrace_C_EXCEPTION

呼び出される関数オブジェクト。

PyTrace_C_RETURN

呼び出される関数オブジェクト。

PyTrace_OPCODE

常に Py_None 。

int PyTrace_CALL

関数やメソッドの新たな呼び出し、またはジェネレータへの新たな進入を報告するときに、Py_tracefunc 関数の what 引数に渡される値です。 ジェネレータ関数からイテレータを作成する時点では、対応するフレーム内の Python バイトコードに制御が移らないため、このイベントは報告されません。

int PyTrace_EXCEPTION

The value of the what parameter to a Py_tracefunc function when an exception has been raised. The callback function is called with this value for what when after any bytecode is processed after which the exception becomes set within the frame being executed. The effect of this is that as exception propagation causes the Python stack to unwind, the callback is called upon return to each frame as the exception propagates. Only trace functions receive these events; they are not needed by the profiler.

int PyTrace_LINE

行番号のイベントを報告するときに、Py_tracefunc 関数 (プロファイリング関数を除く) の what 引数に渡される値です。 フレームの f_trace_lines を 0 に設定すると、そのフレームでは無効にできます。

int PyTrace_RETURN

呼び出しが返るときに Py_tracefunc 関数に what 引数として渡す値です。

int PyTrace_C_CALL

C関数を呼び出す直前に Py_tracefunc 関数の what 引数として渡す値です。

int PyTrace_C_EXCEPTION

C関数が例外を送出したときに Py_tracefunc 関数の what 引数として渡す値です。

int PyTrace_C_RETURN

C関数から戻るときに Py_tracefunc 関数の what 引数として渡す値です。

int PyTrace_OPCODE

新しいオペコードを実行しようとするときに、Py_tracefunc 関数 (プロファイリング関数を除く) の what 引数に渡される値です。 このイベントはデフォルトでは発生しません。 フレームの f_trace_opcodes を 1 に設定して明示的に要求する必要があります。

void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)

プロファイラ関数を func に設定します。 obj はその関数の第 1 引数として渡され、任意の Python オブジェクトまたは NULL を指定できます。 プロファイラ関数が状態を保持する必要がある場合は、スレッドごとに異なる obj を使うと、便利でスレッドセーフな保存先になります。 プロファイラ関数は PyTrace_LINE、PyTrace_OPCODE、PyTrace_EXCEPTION を除くすべての監視対象イベントについて呼び出されます。

sys.setprofile() 関数も参照してください。

The caller must hold the GIL.

void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)

PyEval_SetProfile() と同様ですが、現在のスレッドだけでなく、現在のインタープリタに属する実行中のすべてのスレッドにプロファイラ関数を設定します。

The caller must hold the GIL.

PyEval_SetProfile() と同様に、すべてのスレッドにプロファイラ関数を設定する際に発生した例外を無視します。

Added in version 3.12.

void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)

トレース関数を func に設定します。 PyEval_SetProfile() と同様ですが、トレース関数は行番号のイベントとオペコードごとのイベントを受け取り、C 関数オブジェクトの呼び出しに関連するイベントは受け取りません。 PyEval_SetTrace() で登録したトレース関数には、what 引数として PyTrace_C_CALL、PyTrace_C_EXCEPTION、PyTrace_C_RETURN が渡されることはありません。

sys.settrace() 関数も参照してください。

The caller must hold the GIL.

void PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *obj)

PyEval_SetTrace() と同様ですが、現在のスレッドだけでなく、現在のインタープリタに属する実行中のすべてのスレッドにトレース関数を設定します。

The caller must hold the GIL.

PyEval_SetTrace() と同様に、すべてのスレッドにトレース関数を設定する際に発生した例外を無視します。

Added in version 3.12.

参照のトレース

Added in version 3.13.

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

PyRefTracer_SetTracer() で登録するトレース関数の型です。 第 1 引数は、作成されたばかりの Python オブジェクト (event が PyRefTracer_CREATE の場合)、またはこれから破棄されるオブジェクト (event が PyRefTracer_DESTROY の場合) です。 data 引数は PyRefTracer_SetTracer() の呼び出し時に渡した不透明なポインタです。

Added in version 3.13.

int PyRefTracer_CREATE

Python オブジェクトが作成されたときに、PyRefTracer 関数の event 引数に渡される値です。

int PyRefTracer_DESTROY

The value for the event parameter to PyRefTracer functions when a Python object has been destroyed.

int PyRefTracer_SetTracer(PyRefTracer tracer, void *data)

Register a reference tracer function. The function will be called when a new Python has been created or when an object is going to be destroyed. If data is provided it must be an opaque pointer that will be provided when the tracer function is called. Return 0 on success. Set an exception and return -1 on error.

Note 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. The GIL will be held every time the tracer function is called.

The GIL must be held when calling this function.

Added in version 3.13.

PyRefTracer PyRefTracer_GetTracer(void **data)

登録された参照トレーサ関数と、PyRefTracer_SetTracer() の呼び出し時に登録された不透明なデータポインタの値を取得します。 トレーサが登録されていない場合は NULL を返し、data ポインタを NULL に設定します。

The GIL must be held when calling this function.

Added in version 3.13.

高度なデバッガサポート (advanced debugger support)

以下の関数は高度なデバッグツールでの使用のためだけのものです。

PyInterpreterState *PyInterpreterState_Head()

インタプリタ状態オブジェクトからなるリストのうち、先頭にあるものを返します。

PyInterpreterState *PyInterpreterState_Main()

メインインタプリタの状態オブジェクトを返します。

PyInterpreterState *PyInterpreterState_Next(PyInterpreterState *interp)

インタプリタ状態オブジェクトからなるリストのうち、interp の次にあるものを返します。

PyThreadState *PyInterpreterState_ThreadHead(PyInterpreterState *interp)

インタプリタ interp に関連付けられているスレッドからなるリストのうち、先頭にある PyThreadState オブジェクトを返します。

PyThreadState *PyThreadState_Next(PyThreadState *tstate)

tstate と同じ PyInterpreterState オブジェクトに属しているスレッド状態オブジェクトのうち、 tstate の次にあるものを返します。

スレッドローカルストレージのサポート

Python インタプリタは、スレッドローカルストレージ (thread-local storage, TLS) の低レベルサポートを提供していて、ネイティブの TLS 実装を内部にラップして Python レベルのスレッドローカルストレージ API (threading.local) をサポートしています。 CPython の C レベル API は pthreads や Windows で与えられる TLS と同様です: スレッドキーとスレッドごとに void* 値を関係付ける関数を使います。

The GIL does not need to be held when calling these functions; they supply their own locking.

Python.h は TLS API の宣言を include せず、スレッドローカルストレージを使うには pythread.h を include する必要があることに注意してください。

注釈

この API 関数はどれも void* 値の代わりにメモリ管理を行うことはしません。 メモリの確保と解放は自前で行う必要があります。 void* 値がたまたま PyObject* だった場合は、 API 関数はそれぞれの値の参照カウントの操作は行いません。

スレッド固有ストレージ (Thread Specific Storage, TSS) API

TSS API は、 CPython インタプリタに含まれている既存の TLS API を置き換えるために導入されました。 この API は、スレッドキーの表現に int の代わりに新しい型 Py_tss_t を使います。

Added in version 3.7.

参考

"CPython のスレッドローカルストレージのための新しい C API" (PEP 539)

type Py_tss_t

このデータ構造体はスレッドキーの状態を表現しています。この構造体の定義は、根底の TLS 実装に依存し、キーの初期化状態を表現する内部フィールドを持ちます。 この構造体には公開 (public) のメンバはありません。

Py_LIMITED_API が定義されていないときは、この型の Py_tss_NEEDS_INIT による静的メモリ確保ができます。

Py_tss_NEEDS_INIT

このマクロは Py_tss_t 変数の初期化子に展開されます。 このマクロは Py_LIMITED_API があるときは定義されません。

動的メモリ確保

動的な Py_tss_t のメモリ確保は Py_LIMITED_API でビルドされた拡張モジュールで必要になりますが、その実装がビルド時に不透明なために、この型の静的なメモリ確保は不可能です。

Py_tss_t *PyThread_tss_alloc()
次に属します: Stable ABI (バージョン 3.7 より).

Py_tss_NEEDS_INIT で初期化した値と同じ状態の値を返します。 動的なメモリ確保に失敗した場合は NULL を返します。

void PyThread_tss_free(Py_tss_t *key)
次に属します: Stable ABI (バージョン 3.7 より).

まず PyThread_tss_delete() を呼んで、関連付けられたスレッドローカルな値との対応を解除してから、 PyThread_tss_alloc() で確保した key を解放します。 key 引数が NULL の場合は何もしません。

注釈

解放したキーはダングリングポインタになります。 キーを NULL に設定し直してください。

メソッド

これらの関数の引数 key は NULL であってはなりません。 また、指定された Py_tss_t を PyThread_tss_create() で初期化していなければ、 PyThread_tss_set() と PyThread_tss_get() の動作は未定義です。

int PyThread_tss_is_created(Py_tss_t *key)
次に属します: Stable ABI (バージョン 3.7 より).

指定された Py_tss_t が PyThread_tss_create() で初期化されていれば、0 以外の値を返します。

int PyThread_tss_create(Py_tss_t *key)
次に属します: Stable ABI (バージョン 3.7 より).

TSS キーの初期化に成功すると 0 を返します。 key 引数が指す値を Py_tss_NEEDS_INIT で初期化していなければ、動作は未定義です。 同じキーに対して繰り返し呼び出せます。 初期化済みのキーに対しては何もせず、即座に成功を返します。

void PyThread_tss_delete(Py_tss_t *key)
次に属します: Stable ABI (バージョン 3.7 より).

TSS キーを破棄し、すべてのスレッドでそのキーに関連付けられた値との対応を解除して、キーを未初期化の状態にします。 破棄したキーは PyThread_tss_create() で再び初期化できます。 同じキーに対して繰り返し呼び出せます。 破棄済みのキーに対しては何もしません。

int PyThread_tss_set(Py_tss_t *key, void *value)
次に属します: Stable ABI (バージョン 3.7 より).

現在のスレッドで void* 値を TSS キーに関連付けることに成功すると、0 を返します。 キーから void* 値への対応付けは、スレッドごとに独立しています。

void *PyThread_tss_get(Py_tss_t *key)
次に属します: Stable ABI (バージョン 3.7 より).

現在のスレッドで TSS キーに関連付けられている void* 値を返します。 現在のスレッドでそのキーに値が関連付けられていなければ、NULL を返します。

スレッドローカルストレージ (TLS) API

バージョン 3.7 で非推奨: This API is superseded by Thread Specific Storage (TSS) API.

注釈

このバージョンの API は、ネイティブの TLS キーを安全に int へキャストできないプラットフォームをサポートしません。 そのようなプラットフォームでは、PyThread_create_key() は即座に失敗を示す値を返し、その他の TLS 関数はすべて何もしません。

前述の互換性の問題により、このバージョンのAPIは新規のコードで利用すべきではありません。

int PyThread_create_key()
次に属します: Stable ABI.
void PyThread_delete_key(int key)
次に属します: Stable ABI.
int PyThread_set_key_value(int key, void *value)
次に属します: Stable ABI.
void *PyThread_get_key_value(int key)
次に属します: Stable ABI.
void PyThread_delete_key_value(int key)
次に属します: Stable ABI.
void PyThread_ReInitTLS()
次に属します: Stable ABI.

同期プリミティブ

C API は基本的な相互排他ロックを提供します。

type PyMutex

相互排他ロックです。 PyMutex は、ロックされていない状態を表すために 0 で初期化する必要があります。 例えば次のようにします。

PyMutex mutex = {0};

PyMutex のインスタンスは、コピーしたり移動したりしてはなりません。 PyMutex は内容とアドレスの両方が意味を持つため、書き込み可能なメモリ上の固定された場所に置き続ける必要があります。

注釈

PyMutex は現在 1 バイトを占めますが、このサイズは安定した仕様ではありません。 将来の Python リリースでは、非推奨の期間を設けずにサイズを変更する可能性があります。

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 release the GIL if it is held.

Added in version 3.13.

void PyMutex_Unlock(PyMutex *m)

ミューテックス m のロックを解除します。 ミューテックスはロックされていなければなりません。 ロックされていない場合、この関数は致命的なエラーを発生させます。

Added in version 3.13.

Python Critical Section API

クリティカルセクション API は、フリースレッドの CPython のオブジェクトごとのロックに、デッドロックを避ける層を加えます。 グローバルインタープリタロック への依存を置き換えるためのもので、グローバルインタープリタロックを持つバージョンの Python では何もしません。

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.

The functions and structs used by the macros are exposed for cases where C macros are not available. They should only be used as in the given macro expansions. Note that the sizes and contents of the structures may change in future Python versions.

注釈

2 個のオブジェクトを同時にロックする操作には、Py_BEGIN_CRITICAL_SECTION2 を使う必要があります。 複数のオブジェクトを同時にロックするために、クリティカルセクションを入れ子にすることは できません。 内側のクリティカルセクションが外側のものを中断する場合があるためです。 この API は、3 個以上のオブジェクトを同時にロックする方法を提供しません。

使用例:

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;
}

上の例では、Py_SETREF が Py_DECREF を呼び出し、オブジェクトの解放関数を通じて任意のコードが実行される可能性があります。 ファイナライザが実行するコードがブロックして PyEval_SaveThread() を呼び出した場合、 クリティカルセクション API はランタイムによるクリティカルセクションの一時的な中断を許すことで、再入やロックの順序に起因するデッドロックを避けます。

Py_BEGIN_CRITICAL_SECTION(op)

オブジェクト op のロックを取得し、クリティカルセクションを開始します。

フリースレッドビルドでは、このマクロは次のように展開されます。

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

デフォルトのビルドでは、このマクロは { に展開されます。

Added in version 3.13.

Py_END_CRITICAL_SECTION()

クリティカルセクションを終了し、オブジェクトのロックを解放します。

フリースレッドビルドでは、このマクロは次のように展開されます。

    PyCriticalSection_End(&_py_cs);
}

デフォルトのビルドでは、このマクロは } に展開されます。

Added in version 3.13.

Py_BEGIN_CRITICAL_SECTION2(a, b)

Acquires the per-objects locks for the objects a and b and begins a critical section. The locks are acquired in a consistent order (lowest address first) to avoid lock ordering deadlocks.

フリースレッドビルドでは、このマクロは次のように展開されます。

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

デフォルトのビルドでは、このマクロは { に展開されます。

Added in version 3.13.

Py_END_CRITICAL_SECTION2()

クリティカルセクションを終了し、オブジェクトのロックを解放します。

フリースレッドビルドでは、このマクロは次のように展開されます。

    PyCriticalSection2_End(&_py_cs2);
}

デフォルトのビルドでは、このマクロは } に展開されます。

Added in version 3.13.

Legacy Locking APIs

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

バージョン 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)
次に属します: 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 the GIL.

バージョン 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)
次に属します: Stable ABI.

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

The caller does not need to hold the GIL.

PyLockStatus PyThread_acquire_lock_timed(PyThread_type_lock lock, long long microseconds, int intr_flag)
次に属します: 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 the GIL.

int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
次に属します: 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 the GIL.

int PyThread_release_lock(PyThread_type_lock lock)
次に属します: Stable ABI.

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

The caller does not need to hold the GIL.

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)
次に属します: 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 the GIL.

unsigned long PyThread_get_thread_ident(void)
次に属します: 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 the GIL.

PyObject *PyThread_GetInfo(void)
次に属します: Stable ABI (バージョン 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 the GIL.

PY_HAVE_THREAD_NATIVE_ID

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

unsigned long PyThread_get_thread_native_id(void)
次に属します: 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 the GIL.

void PyThread_exit_thread(void)
次に属します: 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.

警告

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.

void PyThread_init_thread(void)
次に属します: 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)
次に属します: 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 the GIL.

size_t PyThread_get_stacksize(void)
次に属します: 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 the GIL.