Is there a way to determine the total number of threads generated by threading.Thread() (including terminated threads)?

Asked 2 years ago, Updated 2 years ago, 318 views

OS:Windows 10

Despite running threading.Thread() only once, the name attribute of this Thread instance shows that it was Thread-3. I've imported many modules, so I guess I'm making a thread somewhere.

threading.enumerate() looked up the active threads, but only MainThread and Thread-3.

Therefore, I would like to investigate why the thread name became Thread-3.
To do that, I'd like to know how to know the total, including the finished threads, or how to detect when the threads were generated. (You can use other non-python tools.)
Is there such a way?

python python3 multi-threaded

2022-11-05 19:30

2 Answers

How to Detect When Threads Are Generated.
If you want to know the generation of instances of threading.Thread and its derived classes, why don't you put a breakpoint on threading.Thread.__init__?

For example, if you have a code that uses Python threads like the following,

import concurrent.futures
import threading

defprint_thread(id):
    hogename = threading.current_thread().name
    print(f'started: {id} {hogename}')

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    features = {executor.submit(print_thread, id): id for id in range(10)}
    for future in concurrent.futures.as_completed(future):
        print(f'finished: {fures[future]}')

If you make a break point using the debugger pdb, which is difficult to use, regardless of the environment...

 C:\Users\user\python>python-mpdb hoge.py
>c:\users\user\python\hoge.py(1)<module>()
->import concurrent.futures
(Pdb)n
>c:\users\user\python\hoge.py(2)<module>()
->import threading
(Pdb)n
>c:\users\user\python\hoge.py(4)<module>()
->def print_thread(id):
(Pdb)b threading.Thread.__init__
Breakpoint 1 at c:\python38\lib\threading.py:761
(Pdb)c
>c:\python38\lib\threading.py(784)_init__()
- >assert group is None, "group argument must be None for now"
(Pdb)

It stops like this.


2022-11-05 19:30

Even though I've only run threading.Thread() once, the name attribute of this Thread instance shows that it was Thread-3. I've imported a lot of modules, so I guess I'm making threads somewhere.

What is the execution environment?
Even if you import only the threading module,
Threads did not start with Thread-1 when running on jupyter notebook or spyder.
Threads begin with Thread-1 for Python commands, IDLE, and Pycharm.

https://docs.python.org/ja/3.10/library/threading.html
According to

name
String used only for identification.The name has no functional semantics.Multiple threads can have the same name.The initial value of the name is set in the constructor.

and so on.
You don't have to worry too much about the name of the thread.


2022-11-05 19:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.