The active_count() function of Python threading module

Method Name:

threading.active_count()

Overview:

  • The function active_count() returns the number of current threads that are alive within the current program.

  • The active thread count includes the daemon threads(ie., the long running threads that are created with the daemon parameter specified as True in the Thread constructor) and the dummy threads(ie., the threads that are created outside the threading module) 

  • Threads that are created but yet to be started are not included in the active thread count.

Example:

# Example Python program that prints the current active number of threads

import threading

# The function that defines the thread
def threadFunction():
    # Do some work in child thread
    for i in range(1, 10):
        print("Child thread executing..%d"%i)

t1 = threading.Thread(target = threadFunction)

# Start child thread
print("Active thread count: %d"%(threading.active_count()))
t1.start()
print("Active thread count: %d"%(threading.active_count()))

# Do some work in main thread
for i in range(1, 5):
    print("Main thread executing..%d"%i)
print("Active thread count: %d"%(threading.active_count()))
t1.join()

Output:

Active thread count: 1

Child thread executing..1

Active thread count: 2

Child thread executing..2

Child thread executing..3

Main thread executing..1

Child thread executing..4

Child thread executing..5

Main thread executing..2

Child thread executing..6

Child thread executing..7

Main thread executing..3

Child thread executing..8

Main thread executing..4

Child thread executing..9

Active thread count: 2

 


Copyright 2024 © pythontic.com