How to obtain a Thread id in Python?

后端 未结 8 791
时光说笑
时光说笑 2020-12-02 08:01

I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resu

相关标签:
8条回答
  • 2020-12-02 08:49

    You can get the ident of the current running thread. The ident could be reused for other threads, if the current thread ends.

    When you crate an instance of Thread, a name is given implicit to the thread, which is the pattern: Thread-number

    The name has no meaning and the name don't have to be unique. The ident of all running threads is unique.

    import threading
    
    
    def worker():
        print(threading.current_thread().name)
        print(threading.get_ident())
    
    
    threading.Thread(target=worker).start()
    threading.Thread(target=worker, name='foo').start()
    

    The function threading.current_thread() returns the current running thread. This object holds the whole information of the thread.

    0 讨论(0)
  • 2020-12-02 08:56

    I created multiple threads in Python, I printed the thread objects, and I printed the id using the ident variable. I see all the ids are same:

    <Thread(Thread-1, stopped 140500807628544)>
    <Thread(Thread-2, started 140500807628544)>
    <Thread(Thread-3, started 140500807628544)>
    
    0 讨论(0)
提交回复
热议问题