What is threading.active_count() in Python?
Overview
In Python, the method threading.active_co unt() from the threading module is used to count the currently active or running threads.
Syntax
threading.active_count()
Parameters
N/A: This method does not take any argument value.
Return value
Count: This method returns the total currently active thread count.
Code
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.
Explanation
In the above code snippet:
- Line 8: We use the
thread1_Subroutine(i)to get the count of currently active threads. - Line 12: We use the
thread2_Subroutine(i)to get a current active count. - Line 17: We use the
thread3_Subroutine(i)to get the current active count. - Lines 21, 22, and 23: We create three threads,
thread1,thread2, andthread3with their default values liketarget,args, and theirnames. - Line 24: It shows the current thread count at the beginning of the program.
- Lines 26, 27, and 28: We start all three threads created in lines 21, 22, and 23.