首页 > 解决方案 > 在python中启动线程之前从线程对象中检索线程ID

问题描述

在实际启动线程之前,有什么方法可以从线程对象接收线程 ID?例如:

 t = threading.Thread(
                name=...
                target=...
                args=...
)

# I want the id here

t.start()

这是可能的还是有其他解决方法?

谢谢

标签: pythonmultithreading

解决方案


正如我评论的那样,文档明确指出ident(and native_id) 在线程开始之前是 None 。请参阅https://docs.python.org/3/library/threading.html?highlight=ident#threading.Thread.ident

这是一种方法,您可以在线程完成任何有用的操作之前获取identor native_id,使用主代码在启动线程之前获取的信号量,并在 main 准备好让线程继续时释放。

import threading
import time

def threadfunc(word1,word2):
    global s
    print( f"Thread Started" )
    print( f"Thread Acquiring sempahore" )
    s.acquire()
    print( f"Thread Acquired sempahore" )
    print( f"{word1}, {word2}" )
    # do something useful ....
    time.sleep(0.1)
    # wrap-up
    print( f"Thread Releasing sempahore" )
    s.release()
    print( f"Thread Released sempahore" )
    print( "Thread Finished" )

s = threading.Semaphore()

print( f"Main Acquiring sempahore" )
s.acquire()
print( f"Main Acquired sempahore" )

t = threading.Thread(
                name='mythread'
                ,target=threadfunc
                ,args=("hello","world")
    )

# I want the id here
id = t.ident

print( f"Thread id before start: {id}" )

print( "Main starting thread" )
t.start()
print( "Main started thread" )

id1 = t.ident

print( f"Thread id after start: {id1}" )

print( f"Main Releasing sempahore" )
s.release()
print( f"Main Released sempahore" )

t.join()
print( "Main Finished" )

结果:

Main Acquiring sempahore
Main Acquired sempahore
Thread id before start: None
Main starting thread
Thread Started
Main started thread
Thread Acquiring sempahore
Thread id after start: 16932
Main Releasing sempahore
Main Released sempahore
Thread Acquired sempahore
hello, world
Thread Releasing sempahore
Thread Released sempahore
Thread Finished
Main Finished

Semaphore文档在这里https://docs.python.org/3/library/threading.html?highlight=semaphore#threading.Semaphore

其他同步方法是可用的,例如Lock, RLock, 条件等,并且可以很容易地代替Sempahore- 所有这些都在上面的文档链接上。


推荐阅读