_thread --- 低水準の スレッド API


このモジュールはマルチスレッド (別名 軽量プロセス (light-weight processes)または タスク (tasks)) に用いられる低水準プリミティブを提供します --- グローバルデータ空間を共有するマルチスレッドを制御します。同期のための単純なロック (別名 mutexes またはバイナリセマフォ (binary semaphores))が提供されています。 threading モジュールは、このモジュール上で、より使い易く高級なスレッディングの API を提供します。

バージョン 3.7 で変更: このモジュールは以前はオプションでしたが、常に利用可能なモジュールとなりました。

このモジュールでは以下の定数および関数を定義しています:

exception _thread.error

スレッド固有の例外です。

バージョン 3.3 で変更: 現在は組み込みの RuntimeError の別名です。

_thread.LockType

これはロックオブジェクトのタイプです。

_thread.start_new_thread(function, args[, kwargs])

新しいスレッドを開始して、そのIDを返します。スレッドは引数リスト args (タプルでなければなりません)の関数 function を実行します。オプション引数 kwargs はキーワード引数の辞書を指定します。

関数が戻るとき、スレッドは静かに終了します。

When the function terminates with an unhandled exception, sys.unraisablehook() is called to handle the exception. The object attribute of the hook argument is function. By default, a stack trace is printed and then the thread exits (but other threads continue to run).

When the function raises a SystemExit exception, it is silently ignored.

Raises an auditing event _thread.start_new_thread with arguments function, args, kwargs.

バージョン 3.8 で変更: sys.unraisablehook() is now used to handle unhandled exceptions.

_thread.interrupt_main(signum=signal.SIGINT, /)

Simulate the effect of a signal arriving in the main thread. A thread can use this function to interrupt the main thread, though there is no guarantee that the interruption will happen immediately.

If given, signum is the number of the signal to simulate. If signum is not given, signal.SIGINT is simulated.

If the given signal isn't handled by Python (it was set to signal.SIG_DFL or signal.SIG_IGN), this function does nothing.

バージョン 3.10 で変更: The signum argument is added to customize the signal number.

注釈

This does not emit the corresponding signal but schedules a call to the associated handler (if it exists). If you want to truly emit the signal, use signal.raise_signal().

_thread.exit()

SystemExit を送出します。それが捕えられないときは、静かにスレッドを終了させます。

_thread.allocate_lock()

新しいロックオブジェクトを返します。ロックのメソッドはこの後に記述されます。ロックは初期状態としてアンロック状態です。

_thread.get_ident()

現在のスレッドの 'スレッドID' を返します。非ゼロの整数です。この値は直接の意味を持っていません; 例えばスレッド特有のデータの辞書に索引をつけるためのような、マジッククッキーとして意図されています。スレッドが終了し、他のスレッドが作られたとき、スレッド ID は再利用されるかもしれません。

_thread.get_native_id()

Return the native integral Thread ID of the current thread assigned by the kernel. This is a non-negative integer. Its value may be used to uniquely identify this particular thread system-wide (until the thread terminates, after which the value may be recycled by the OS).

利用可能な環境: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD。

バージョン 3.8 で追加.

_thread.stack_size([size])

新しいスレッドを作るときのスレッドスタックサイズを返します。オプションの size 引数にはこれ以降に作成するスレッドのスタックサイズを指定し、0 (プラットフォームのデフォルト値または設定されたデフォルト値) か、 32,768 (32 KiB) 以上の正の整数でなければなりません。size が指定されない場合 0 が使われます。スレッドのスタックサイズの変更がサポートされていない場合、 RuntimeError を送出します。不正なスタックサイズが指定された場合、 ValueError を送出して、スタックサイズは変更されません。32 KiB は現在のインタープリタ自身のために十分であると保証された最小のスタックサイズです。いくつかのプラットフォームではスタックサイズに対して制限があることに注意してください。例えば最小のスタックサイズが 32 KiB より大きかったり、システムのメモリページサイズ の整数倍の必要があるなどです。この制限についてはプラットフォームのドキュメントを参照してください (一般的なページサイズは 4 KiB なので、プラットフォームに関する情報がない場合は 4096 の整数倍のスタックサイズを選ぶといいかもしれません)。

利用可能な環境: Windows, pthreads。

Unix platforms with POSIX threads support.

_thread.TIMEOUT_MAX

The maximum value allowed for the timeout parameter of Lock.acquire. Specifying a timeout greater than this value will raise an OverflowError.

バージョン 3.2 で追加.

ロックオブジェクトは次のようなメソッドを持っています:

lock.acquire(blocking=True, timeout=-1)

オプションの引数なしで使用すると、このメソッドは他のスレッドがロックしているかどうかにかかわらずロックを獲得します。ただし、他のスレッドがすでにロックしている場合には解除されるまで待ってからロックを獲得します (同時にロックを獲得できるスレッドはひとつだけであり、これこそがロックの存在理由です)。

blocking 引数を指定すると、その値によって動作が変わります。偽であれば、待たずにすぐ獲得できる場合にだけロックを獲得します。真であれば、先の例と同様、ロックの状態にかかわらず獲得をおこないます。

timeout 引数に正の float 値が指定された場合、返る前に待つ最大の時間を秒数で指定します。負の timeout 引数は無制限に待つことを指定します。blocking が偽の時は timeout を指定することはできません。

なお、ロックを獲得できた場合は True、できなかった場合は False を返します。

バージョン 3.2 で変更: 新しい timeout 引数。

バージョン 3.2 で変更: POSIX ではロックの取得がシグナルに割り込まれるようになりました。

lock.release()

ロックを解放します。そのロックは既に獲得されたものでなければなりませんが、しかし同じスレッドによって獲得されたものである必要はありません。

lock.locked()

ロックの状態を返します: 同じスレッドによって獲得されたものなら True 、違うのなら False を返します。

これらのメソッドに加えて、ロックオブジェクトは with 文を通じて以下の例のように使うこともできます。

import _thread

a_lock = _thread.allocate_lock()

with a_lock:
    print("a_lock is locked while this executes")

警告:

  • スレッドは割り込みと奇妙な相互作用をします: KeyboardInterrupt 例外は任意のスレッドによって受け取られます。 (signal モジュールが利用可能なとき、割り込みは常にメインスレッドへ行きます。)

  • sys.exit() を呼び出す、あるいは SystemExit 例外を送出することは、 _thread.exit() を呼び出すことと同じです。

  • It is not possible to interrupt the acquire() method on a lock --- the KeyboardInterrupt exception will happen after the lock has been acquired.

  • メインスレッドが終了したとき、他のスレッドが生き残るかどうかは、システムに依存します。多くのシステムでは、 try ... finally 節や、オブジェクトデストラクタを実行せずに終了されます。

  • メインスレッドが終了したとき、それの通常のクリーンアップは行なわれず、 (try ... finally 節が尊重されることは除きます)、標準 I/O ファイルはフラッシュされません。