如何只获取当前线程号?

How to get only the current thread number?

这是我使用的示例代码

import time
import threading
import re

def do_action():
    while True:
        x = threading.current_thread()
        print(x)
        time.sleep(60)

for _ in range(1):
    threading.Thread(target=do_action).start()

打印结果如下

<Thread(Thread-1, started 10160)>

我只需要获取线程的编号,在本例中为编号 1

我尝试使用

thread_number = re.findall("(\d+)", x)[0]

但是使用时出现错误

尝试:

thread_number = re.findall("(\d+)", x.name)[0]

如果您没有明确为线程命名,Thread-1 输出中的 1 是默认线程名称生成的一部分。 无法保证线程会有这样的编号——主线程不会,显式命名的线程通常不会。此外,如果手动为线程指定与 Thread-n 模式匹配的名称,则多个线程可以具有相同的编号。

如果这是你想要的数字,你可以通过解析线程的名称来获得它 - int(thread.name.split('-')[1]) - 但它可能不是你计划使用它的任何工作的最佳工具。


如果您启动了一堆线程并且由于某种原因它们每个都需要使用从 1 到 n 的不同数字,可能是工作分配或其他原因,只需将一个数字传递给它们的目标函数:

def do_stuff(n):
    # do stuff with n

threads = [threading.Thread(target=do_stuff, args=(i,)) for i in range(1, 11)]
for thread in threads:
    thread.start()

线程也有identnative_id属性,None表示还没有启动的线程,整数表示已经启动的线程。这些标识符保证对于同时处于活动状态的线程是不同的 - 这种独特性保证对于 ident 是进程范围的,对于 native_id 是系统范围的。但是,如果一个线程在另一个线程开始之前完成,则可能会为它们分配相同的 identnative_id.