LoginSignup
3
2

More than 3 years have passed since last update.

pythonでスレッドのIDを取得する

Posted at

何がしたかったのか

既存のソースコードの改修が発端です。
複数回並列で行える処理で最新のスレッドだけが動作するような作りにしたかった。
並列して動くスレッドのIDは別個のものが振られるため、IDを取得できればうまく動かせるのではと考えた。

※ その設計がいいとは限らないです。
  ちゃんと状態管理してあげるのが正しいんだろうけど
  手早く済ませたかったのでこんなやり方をしてます。

検証環境

OS: Ubuntu 18.04
python: 3.6.7

使うモジュール・関数

  • threadingモジュール
    • get_ident()

これでスレッドIDは取得できるとのことなので、
後は下のサンプルコードで並行で動いているスレッドがちゃんと別のIDを返してくるかだけ確認する

サンプルコード

thread_id_test.py
import threading as th
import time

def say_th_id(secouds, th_no):
    time.sleep(secouds)
    print("thread no:{0}, ident:{1}".format(th_no, th.get_ident()))

if __name__ == "__main__":
    th1 = th.Thread(target=say_th_id, args=(6,1))
    th2 = th.Thread(target=say_th_id, args=(5,2))
    th1.start()
    time.sleep(1.0)
    th2.start()

結果

thread no:1, ident:139790510892800
thread no:2, ident:139790502500096

ちゃんと別々のスレッドIDが取得できました。
解釈違いなどあればコメントをください!

参考にしたサイト

multithreading - How to find a thread id in Python - Stack Overflow

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2