In Python, the method threading.active_co unt()
from the threading
module is used to count the currently active or running threads.
threading.active_count()
N/A
: This method does not take any argument value.
Count
: This method returns the total currently active thread count.
The code below demonstrates how to use active_count()
in a program:
# Program to count active threads# active_count() method from Threading Moduleimport threadingimport time# Methods for three threads..def thread1_Subroutine(i):time.sleep(2)print("Thread-1: Number of active threads:", threading.active_count())print('Thread 1 Value:', i)def thread2_Subroutine(i):print("Thread-2: Number of active threads:", threading.active_count())print('Thread 2 Value:', i)def thread3_Subroutine(i):time.sleep(5)print("Thread-3: Number of active threads:", threading.active_count())print("Thread 3 Value:", i)# Creating sample threadsthread1 = threading.Thread(target=thread1_Subroutine, args=(100,), name="Thread1")thread2 = threading.Thread(target=thread2_Subroutine, args=(200,), name="Thread2")thread3 = threading.Thread(target=thread3_Subroutine, args=(300,), name="Thread3")print("START: Current active thread count: ", threading.active_count())# Calling start() method to initialize executionthread1.start()thread2.start()thread3.start()thread3.join() # Wait for thread-3 to join.
In the above code snippet:
thread1_Subroutine(i)
to get the count of currently active threads.thread2_Subroutine(i)
to get a current active count.thread3_Subroutine(i)
to get the current active count.thread1
, thread2
, and thread3
with their default values like target
, args
, and their names
.