python关闭线程根据id_python线程的ID和Name

多线程环境下用来区分不同线程的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 --

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值