2020年5月18日 / 4,172次阅读 / Last Modified 2020年5月18日
多线程
多线程环境下用来区分不同线程的ID和Name。线程name在创建的时候可由用户设定。
import threading
def _show_id_name():
print(threading.current_thread().name)
print(threading.current_thread().ident)
print(threading.get_ident())
th = threading.Thread(target=_show_id_name, name='testing thread',
args=(), daemon=True)
th.start()
th.join()
在线程中调用threading.current_thread()函数获取当前线程对象,然后在获得name和ident(ID)。代码中还直接使用了threading.get_ident()函数获取当前线程ID。运行效果:
E:\py>python t_id_name.py
testing thread
6264
6264
E:\py>python t_id_name.py
testing thread
5380
5380
E:\py>python t_id_name.py
testing thread
1500
1500
线程name是代码指定的,而id每次运行都不一样。下面是关于threading.get_ident()函数的的说明:
Return the ‘thread identifier’ of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created.
相同Name的线程每次运行的ID都可能不一样,此ID无特别意义,在线程结束后,此ID还可能出现在其它线程中。
-- EOF --
本文链接:https://www.pynote.net/archives/1951
©Copyright 麦新杰 Since 2019 Python笔记