'Why do I see more threads at OS level than are spawned by my code?

Python programs generates threads on some conditions with the following code:

thread1 = threading.Thread(target=foo, args=(arg1,))
thread1.start()

The problem is that I see too many threads at OS level:

$ ps -efL | grep myscript.py | wc -l
4117

However, in the program, with threading.enumerate() or threading.active_count(), the thread count is just 200.

What are the remaining threads? Are they inactive? Is there a way to check the function name of those 4000+ threads?



Solution 1:[1]

It is weird, but there is posibility that those 4000 threads are all threads from your PC, for example right now i have 3840 active Threads, and python should not give you all tasks from your pc. In python if you have only MainThread you should see 1 after typing threading.active_count(), or more if you create and start other tasks. You cant see all threads name, you can see only those which are related to your python program. Typing:

for x in threading.enumerate():
    print(x.getName())

Will show you all threads in this session with their name

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Przemosz