Home »
Python »
Python Reference »
Python threading Module
Python threading Module | enumerate() Method with Example
Python threading.enumerate() Method: Here, we are going to learn about the getName() method of threading Module in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on May 14, 2020
Python threading.enumerate() Method
enumerate() is an inbuilt method of the threading module in Python. It is used to return the list of all the Thread class objects which are currently alive. It also includes daemonic threads, the main thread, and dummy thread objects created by current_thread(). It does not count the threads that have terminated or which have not started yet.
Module:
import threading
Syntax:
enumerate()
Parameter(s):
Return value:
The return type of this method is <class 'list'>, it returns a list of the currently alive Thread class objects.
Example:
# Python program to explain the use of
# enumerate() method in the Threading Module
import time
import threading
def thread_1(i):
time.sleep(5)
print("Threads alive when thread_1 executes:")
print(*threading.enumerate(), sep = "\n")
print()
def thread_2(i):
print("Threads alive when thread_2 executes")
print(*threading.enumerate(), sep = "\n")
print()
def thread_3(i):
time.sleep(4)
def thread_4(i):
time.sleep(1)
print("Threads alive when thread_4 executes")
print(*threading.enumerate(), sep = "\n")
print()
# Creating sample threads
thread1 = threading.Thread(target=thread_1, args=(10,))
thread2 = threading.Thread(target=thread_2, args=(20,))
thread3 = threading.Thread(target=thread_3, args=(30,))
thread4 = threading.Thread(target=thread_4, args=(50,))
print("Threads alive in the starting:", threading.enumerate())
print()
# Starting the threads
thread1.start()
thread2.start()
thread3.start()
thread4.start()
Output
Threads alive in the starting: [<_MainThread(MainThread, started 139862202693376)>]
Threads alive when thread_2 executes
<_MainThread(MainThread, started 139862202693376)>
<Thread(Thread-1, started 139862176597760)>
<Thread(Thread-2, started 139862168205056)>
Threads alive when thread_4 executes
<_MainThread(MainThread, stopped 139862202693376)>
<Thread(Thread-1, started 139862176597760)>
<Thread(Thread-3, started 139862159812352)>
<Thread(Thread-4, started 139862168205056)>
Threads alive when thread_1 executes:
<_MainThread(MainThread, stopped 139862202693376)>
<Thread(Thread-1, started 139862176597760)>