Search code examples
pythonmultithreadingpython-multithreading

When does Python reset the thread count?


Assume a main program that creates 5 threads, one at a time:

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

When the thread is started, it prints its name with threading.currentThread().getName(), resulting in the following output:

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

How come the name of the thread keeps increasing? I assumed that Python would reset the Thread-xxx number after deleting each thread after its execution with del thread_1.

This was the expected output:

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

Solution

  • I don't think you can assume that the number at the end of the name corresponds to the number of currently active threads:

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

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

    For example, the following code doesn't even start the threads, but immediately deletes them:

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

    And still prints:

    Thread-1
    Thread-2
    Thread-3
    

    Update: Just had a look at the implementation of threading.py at CPython, where Thread.__init__ calls _newname if no name is given.

    # 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()
    

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

    That counter will just keep increasing.