Python threading enumerate() Method with Example

Python threading.enumerate() Method: In this tutorial, we will learn about the enumerate() method of threading module in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 23, 2023

Python threading.enumerate() Method

The threading.enumerate() is an inbuilt method of the threading module, 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

The following module is required to use enumerate() method:

import threading

Syntax

The following is the syntax of enumerate() method:

enumerate()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is <class 'list'>, it returns a list of the currently alive Thread class objects.

Example of threading.enumerate() Method in Python

# 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)>



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.