_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 - SystemExitexception, it is silently ignored.- Raises an auditing event - _thread.start_new_threadwith 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.SIGINTis simulated.- If the given signal isn't handled by Python (it was set to - signal.SIG_DFLor- 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). - Availability: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD, Solaris. - Added in version 3.8. - バージョン 3.13 で変更: Added support for GNU/kFreeBSD. - バージョン 3.15 で変更: Added support for Solaris. 
- _thread.stack_size([size])¶
- 新しいスレッドを作るときのスレッドスタックサイズを返します。オプションの size 引数にはこれ以降に作成するスレッドのスタックサイズを指定し、0 (プラットフォームのデフォルト値または設定されたデフォルト値) か、 32,768 (32 KiB) 以上の正の整数でなければなりません。size が指定されない場合 0 が使われます。スレッドのスタックサイズの変更がサポートされていない場合、 - RuntimeErrorを送出します。不正なスタックサイズが指定された場合、- ValueErrorを送出して、スタックサイズは変更されません。32 KiB は現在のインタープリタ自身のために十分であると保証された最小のスタックサイズです。いくつかのプラットフォームではスタックサイズに対して制限があることに注意してください。例えば最小のスタックサイズが 32 KiB より大きかったり、システムのメモリページサイズ の整数倍の必要があるなどです。この制限についてはプラットフォームのドキュメントを参照してください (一般的なページサイズは 4 KiB なので、プラットフォームに関する情報がない場合は 4096 の整数倍のスタックサイズを選ぶといいかもしれません)。- Availability: 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.- Added in version 3.2. 
ロックオブジェクトは次のようなメソッドを持っています:
- lock.acquire(blocking=True, timeout=-1)¶
- オプションの引数なしで使用すると、このメソッドは他のスレッドがロックしているかどうかにかかわらずロックを獲得します。ただし、他のスレッドがすでにロックしている場合には解除されるまで待ってからロックを獲得します (同時にロックを獲得できるスレッドはひとつだけであり、これこそがロックの存在理由です)。 - If the blocking argument is present, the action depends on its value: if it is false, the lock is only acquired if it can be acquired immediately without waiting, while if it is true, the lock is acquired unconditionally as above. - If the floating-point timeout argument is present and positive, it specifies the maximum wait time in seconds before returning. A negative timeout argument specifies an unbounded wait. You cannot specify a timeout if blocking is false. - なお、ロックを獲得できた場合は - True、できなかった場合は- Falseを返します。- バージョン 3.2 で変更: 新しい timeout 引数。 - バージョン 3.2 で変更: POSIX ではロックの取得がシグナルに割り込まれるようになりました。 - バージョン 3.14 で変更: Lock acquires can now be interrupted by signals on Windows. 
- 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")
警告:
- Interrupts always go to the main thread (the - KeyboardInterruptexception will be received by that thread.)
- sys.exit()を呼び出す、あるいは- SystemExit例外を送出することは、- _thread.exit()を呼び出すことと同じです。
- メインスレッドが終了したとき、他のスレッドが生き残るかどうかは、システムに依存します。多くのシステムでは、 - try...- finally節や、オブジェクトデストラクタを実行せずに終了されます。