Saturday, 12 December 2015

Python: Get number of live threads

‘threading.active_count()’ method is used to get number of active threads at present. The returned count is equal to the length of the list returned by enumerate().


MyThread.py
import threading
import time

class MyThread(threading.Thread):
 def run(self):
  time.sleep(1)
  print(threading.current_thread().getName(), " Finished")

thread1 = MyThread(name="Thread_1")
thread2 = MyThread(name="Thread_2")
thread3 = MyThread(name="Thread_3")

thread1.start()
thread2.start()
thread3.start()

print("Active threads are ", threading.active_count())
time.sleep(2)
print("Active threads are ", threading.active_count())


Sample Output
$ python3 MyThread.py 
Active threads are  4
Thread_1  Finished
Thread_3  Finished
Thread_2  Finished
Active threads are  1


Previous                                                 Next                                                 Home

No comments:

Post a Comment