Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python getting running Threads

I'm doing a project with python and in my code i had to start some threads. Now i need to call a thread to stop it from, but from another class. Is there some way to get a list of all running threads?

Thanks for help.

like image 561
Davide Ruzza Avatar asked Jun 21 '16 09:06

Davide Ruzza


People also ask

How do you see what threads are running Python?

In Python, the method threading. active_co unt() from the threading module is used to count the currently active or running threads.

How do I get the active thread name in Python?

get_ident() works, or threading. current_thread(). ident (or threading. currentThread().

How do I make a list of threads in Python?

Creating Thread Using Threading ModuleDefine a new subclass of the Thread class. Override the __init__(self [,args]) method to add additional arguments. Then, override the run(self [,args]) method to implement what the thread should do when started.


2 Answers

You can use threading.enumerate() : Python documentation about it here

for thread in threading.enumerate():      print(thread.name) 
like image 183
kaiser Avatar answered Oct 06 '22 12:10

kaiser


threading.enumerate() can be used for getting the list of running threads (Thread objects). As per library reference, running threads imply

  1. All Thread objects that are currently alive, created using threading module
  2. Daemonic threads (whose presence doesn't prevent the process from exiting)
  3. Dummy thread objects created by current thread (Threads directly created from C code. They are always alive and daemonic and cannot be joined)
  4. Main Thread (Default thread in python)

It excludes Threads that are not yet started and already terminated.

You can use threading.active_count to get the length of the list returned by threading.enumerate

like image 25
Vineel Avatar answered Oct 06 '22 12:10

Vineel