python - 在python中启动线程之前从线程对象中检索线程ID
问题描述
在实际启动线程之前,有什么方法可以从线程对象接收线程 ID?例如:
t = threading.Thread(
name=...
target=...
args=...
)
# I want the id here
t.start()
这是可能的还是有其他解决方法?
谢谢
解决方案
正如我评论的那样,文档明确指出ident
(and native_id
) 在线程开始之前是 None 。请参阅https://docs.python.org/3/library/threading.html?highlight=ident#threading.Thread.ident
这是一种方法,您可以在线程完成任何有用的操作之前获取ident
or 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
- 所有这些都在上面的文档链接上。
推荐阅读
- javascript - 如何在对象函数中引用对象数据?
- python - 如何使 matplotlib 在 AWS EMR Jupyter 笔记本中工作?
- python - 如何使用 Keras 回调在 Tensorboard 中可视化平均编辑距离?
- python - 调整DataFrame中的异常格式,函数继续返回None
- json - 使用 T-SQL OPENJSON 和 SELECT * 时 VS 崩溃
- salesforce - 无法为 Salesforce 运行 Lightning 测试服务 (LTS)
- gatsby - 如何查找使用 gatsby-remark-copy-linked-files 导入的图像的路径?
- npm - 如何在 Mac 上使用 NPM 安装 Bulksplash
- react-native - 如何将“链接”转移到另一个组件?
- python - 无法下载匀称的包