Python 什么时候重置线程数?

When does Python reset the thread count?

假设一个主程序创建了 5 个线程,一次一个:

main.py

import threading
import time
from camera import Camera  # this class inherits threading.Thread

# Initialize lock
lock = threading.RLock()

for i in range(5):

    # Initialize camera threads
    thread_1 = Camera(lock)

    # Start videorecording
    thread_1.start()

    time.sleep(100)

    # Signal thread to finish
    thread_1.stop()

    # Wait for thread to finish
    thread_1.join()

    del thread_1

当线程启动时,它用 threading.currentThread().getName() 打印它的名字,导致以下输出:

Thread-1
Thread-2
Thread-3
Thread-4
Thread-5

怎么线程的名字一直在变大?我假设 Python 会在使用 del thread_1.

删除每个线程后重置 Thread-xxx 编号

这是预期的输出:

Thread-1
Thread-1
Thread-1
Thread-1
Thread-1

我认为您不能假设名称末尾的数字对应于当前活动线程的数量:

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

来源:https://docs.python.org/3/library/threading.html#threading.Thread

例如,下面的代码甚至没有启动线程,而是立即删除它们:

import threading
for _ in range(3):
    t = threading.Thread()
    print(t.name)
    del t

并且仍然打印:

Thread-1
Thread-2
Thread-3

更新: 刚刚查看了 CPython 中 threading.py 的实现,如果没有给出名称,Thread.__init__ 调用 _newname .

# Helper to generate new thread names
_counter = _count().__next__
_counter() # Consume 0 so first non-main thread has id 1.
def _newname(template="Thread-%d"):
    return template % _counter()

来源:https://github.com/python/cpython/blob/d0acdfcf345b44b01e59f3623dcdab6279de686a/Lib/threading.py#L738

那个计数器会一直增加。