Nearby lessons

138 of 159

Python - Thread Information and Methods

📌 What You Will Learn
  • Set and get the name of a thread using the name property
  • Read the thread identification number with ident
  • Count active threads with active_count()
  • List all active threads with enumerate()
  • Check thread status with is_alive() and wait with join()

Setting and Getting Name of a Thread

Every thread in Python has a name.

The thread name may be:

  • A default name generated by Python
  • A customized name provided by the programmer

Thread names are useful for identifying different threads while executing and debugging a multithreaded program.

Thread
  │
  ├── Name
  ├── Identification Number
  └── Other Thread Information

Thread Class Methods for Thread Name

We can get and set the name of a thread using the following methods:

Method Description
t.name Returns the name of the thread
t.name = newName Sets a new name for the thread

Example:

t.name

t.name = "MyThread"

Important Note - name Variable

Every Thread has an implicit variable:

name

This variable represents the name of the Thread.

Therefore, we can also access the thread name using:

t.name

For the current executing thread:

current_thread().name

Hence, the thread name can be obtained using:

current_thread().name

or:

current_thread().name

Program - Setting and Getting Name of Current Thread

🐍Code Cell
1from threading import *
2 
3print(current_thread().name)
4 
5current_thread().name = "Pawan Kalyan"
6 
7print(current_thread().name)
8 
9print(current_thread().name)
Output
No output captured.

Output

Program Explanation - Thread Name

Step 1: Import Everything from threading

from threading import *

This imports the required threading classes and functions.


Step 2: Display the Current Thread Name

print(current_thread().name)

current_thread() returns the currently executing Thread object.

At this point, only the default Main Thread is executing.

Therefore:

current_thread().name

returns:

MainThread

Step 3: Change the Current Thread Name

current_thread().name = "Pawan Kalyan"

name changes the name of the current thread.

Therefore:

MainThread
    │
    ▼
current_thread().name = "Pawan Kalyan"
    │
    ▼
Pawan Kalyan

Step 4: Display the Updated Thread Name

print(current_thread().name)

The current thread has already been renamed.

Therefore, the output is:

Pawan Kalyan

Step 5: Access the name Variable

print(current_thread().name)

Every Thread has an implicit variable called name.

It also contains the current thread name.

Therefore, the output is again:

Pawan Kalyan

Execution Flow - Setting and Getting Thread Name

Program Starts
      │
      ▼
Current Thread
      │
      ▼
MainThread
      │
      ▼
name property
      │
      ▼
Print MainThread
      │
      ▼
current_thread().name = "Pawan Kalyan"
      │
      ▼
Thread Name Changed
      │
      ▼
name property
      │
      ▼
Print Pawan Kalyan
      │
      ▼
Access name Property
      │
      ▼
Print Pawan Kalyan

the name property

Member Purpose Example
name Gets thread name t.name
name Changes thread name t.name = "MyThread"
name Represents the thread name t.name

Modern Python Note

The source document uses:

name property
name property

Modern Python prefers the name property, and the examples in this topic use it:

# Get thread name
print(current_thread().name)

# Change thread name
current_thread().name = "Pawan Kalyan"

# Get updated name
print(current_thread().name)

This produces the same thread-name concept in a more current style.

Thread Identification Number - ident

For every thread, internally a unique identification number is available.

We can access this identification number using the implicit variable:

ident

Simple Definition:

ident represents the identification number of a Thread.

Syntax:

thread_object.ident

For the current thread:

current_thread().ident

For a Child Thread object:

t.ident

Thread Identification Diagram

Python Program
     │
     ├───────────────┐
     │               │
     ▼               ▼
Main Thread       Child Thread
     │               │
     ▼               ▼
   ident            ident
     │               │
     ▼               ▼
Unique ID          Unique ID

Each thread has its own thread identification number.

Program - Thread Identification Number

🐍Code Cell
1from threading import *
2 
3def test():
4 print("Child Thread")
5 
6t = Thread(target=test)
7t.start()
8 
9print("Main Thread Identification Number:",
10 current_thread().ident)
11 
12print("Child Thread Identification Number:",
13 t.ident)
Output
No output captured.

Output

Important Note About ident Output

The identification numbers shown in the output are only example values.

2492
2768

The actual identification numbers may be different for each execution or environment.

Therefore, we should not expect:

2492
2768

every time the program runs.

Program Explanation - Thread Identification Number

Step 1: Create the Child Thread Function

def test():
    print("Child Thread")

The test() function contains the work of the Child Thread.


Step 2: Create the Thread Object

t = Thread(target=test)

A Child Thread object is created.

Its target function is:

test

Step 3: Start the Child Thread

t.start()

The Child Thread begins executing the test() function.

It prints:

Child Thread

Step 4: Get Main Thread Identification Number

current_thread().ident

This statement is executed by the Main Thread.

current_thread() returns the Main Thread object and ident gives its identification number.

Example:

Main Thread Identification Number: 2492

Step 5: Get Child Thread Identification Number

t.ident

The variable t refers to the Child Thread object.

Therefore, t.ident returns the identification number of the Child Thread.

Example:

Child Thread Identification Number: 2768

Execution Flow - Thread Identification Number

Program Starts
      │
      ▼
Create test()
      │
      ▼
Create Child Thread
      │
      ▼
t = Thread(target=test)
      │
      ▼
Start Child Thread
      │
      ▼
Child Thread Executes test()
      │
      ▼
Print "Child Thread"
      │
      ▼
Get Main Thread ident
      │
      ▼
current_thread().ident
      │
      ▼
Get Child Thread ident
      │
      ▼
t.ident
      │
      ▼
Display Identification Numbers

active_count() Function

The active_count() function returns the number of Thread objects that are currently active.

Simple Definition:

active_count() returns the number of active threads currently running.

Syntax:

active_count()

For example, if only the Main Thread is active:

active_count()
      │
      ▼
1

If the Main Thread and three Child Threads are active:

MainThread
ChildThread1
ChildThread2
ChildThread3

Total = 4

Program - active_count()

🐍Code Cell
1from threading import *
2import time
3 
4def display():
5 print(current_thread().name, ".started")
6 time.sleep(3)
7 print(current_thread().name, ".ended")
8 
9print("The Number of active Threads:", active_count())
10 
11t1 = Thread(target=display, name="ChildThread1")
12t2 = Thread(target=display, name="ChildThread2")
13t3 = Thread(target=display, name="ChildThread3")
14 
15t1.start()
16t2.start()
17t3.start()
18 
19print("The Number of active Threads:", active_count())
20 
21time.sleep(5)
22 
23print("The Number of active Threads:", active_count())
Output
No output captured.

Output - active_count()

Program Explanation - active_count()

Step 1: Import Required Modules

from threading import *
import time

The threading module provides thread-related functionality.

The time module is used to pause execution using sleep().


Step 2: Create display()

def display():
    print(current_thread().name, ".started")
    time.sleep(3)
    print(current_thread().name, ".ended")

The function:

  1. Prints the current thread name with .started.
  2. Waits for 3 seconds.
  3. Prints the current thread name with .ended.

Step 3: Check Initial Active Thread Count

print("The Number of active Threads:", active_count())

Initially, only the Main Thread is running.

Therefore:

active_count() = 1

Output:

The Number of active Threads: 1

Step 4: Create Three Child Threads

t1 = Thread(target=display, name="ChildThread1")
t2 = Thread(target=display, name="ChildThread2")
t3 = Thread(target=display, name="ChildThread3")

Three Child Thread objects are created.

Each Thread is also given a custom name directly through the name argument.

Thread Object Thread Name Target
t1 ChildThread1 display
t2 ChildThread2 display
t3 ChildThread3 display

Step 5: Start All Three Threads

t1.start()
t2.start()
t3.start()

All three Child Threads begin executing the display() function.

Each thread prints its own name:

ChildThread1 .started
ChildThread2 .started
ChildThread3 .started

Step 6: Count Active Threads Again

print("The Number of active Threads:", active_count())

At this point, the following threads are active:

  1. MainThread
  2. ChildThread1
  3. ChildThread2
  4. ChildThread3

Therefore:

active_count() = 4

Output:

The Number of active Threads: 4

Step 7: Main Thread Waits for 5 Seconds

time.sleep(5)

The Main Thread pauses for five seconds.

Each Child Thread only sleeps for three seconds.

Therefore, during this five-second period, all three Child Threads complete their execution.

They print:

ChildThread1 .ended
ChildThread2 .ended
ChildThread3 .ended

Step 8: Check Active Thread Count Again

print("The Number of active Threads:", active_count())

All three Child Threads have completed.

Only the Main Thread remains active.

Therefore:

active_count() = 1

Output:

The Number of active Threads: 1

How active_count() Changes

Program Starts
      │
      ▼
Only MainThread
      │
      ▼
active_count()
      │
      ▼
      1
      │
      ▼
Create t1, t2, t3
      │
      ▼
Start t1, t2, t3
      │
      ▼
┌─────────────────┐
│ MainThread      │
│ ChildThread1    │
│ ChildThread2    │
│ ChildThread3    │
└─────────────────┘
      │
      ▼
active_count()
      │
      ▼
      4
      │
      ▼
Child Threads Complete
      │
      ▼
Only MainThread
      │
      ▼
active_count()
      │
      ▼
      1

Execution Flow - active_count()

Program Starts
      │
      ▼
Main Thread Running
      │
      ▼
active_count() = 1
      │
      ▼
Create ChildThread1
Create ChildThread2
Create ChildThread3
      │
      ▼
Start All Threads
      │
      ▼
All Child Threads
Execute display()
      │
      ▼
active_count() = 4
      │
      ▼
Main Thread
sleep(5)
      │
      ▼
Child Threads Finish
After About 3 Seconds
      │
      ▼
Only MainThread Remains
      │
      ▼
active_count() = 1

Thread Name, ident and active_count() Comparison

Method / Variable Purpose Example
name Returns thread name t.name
name Changes thread name t.name = "MyThread"
name Represents thread name t.name
ident Returns thread identification number t.ident
active_count() Returns number of currently active threads active_count()

Complete Summary

In this part, we learned how to get important information about Python threads.

Topic Description
Thread Name Every Python Thread has a name.
Default Name Python can automatically provide a thread name.
Custom Name A programmer can assign a custom name.
name Returns the thread name.
name Changes the thread name.
name Implicit variable/property representing thread name.
ident Identification number associated with a Thread.
active_count() Returns the number of active threads currently running.

Important Notes

  1. Every Python Thread has a name.
  2. The thread name may be the default name generated by Python or a custom name provided by the programmer.
  3. name returns the name of a Thread.
  4. name changes the name of a Thread.
  5. Every Thread has an implicit variable/property called name.
  6. The name property can also be used to access the thread name.
  7. The original document uses name and name. Modern Python code generally prefers the name property.
  8. Every Thread has an identification number available through ident.
  9. current_thread().ident returns the identification number of the currently executing Thread.
  10. t.ident returns the identification number associated with the Thread object t.
  11. The exact ident values shown in an example should not be expected on every execution.
  12. active_count() returns the number of currently active threads.
  13. Initially, a normal Python program has the Main Thread, so the example shows active_count() as 1.
  14. When three Child Threads and the Main Thread are active, the example shows an active count of 4.
  15. After all three Child Threads finish, only the Main Thread remains, so the count becomes 1 again.

enumerate() Function

The enumerate() function returns a list of all active threads currently running.

Simple Definition:

enumerate() returns a list containing all currently active Thread objects.

Syntax:

enumerate()

Example:

l = enumerate()

The variable l contains the list of active Thread objects.

We can iterate over this list:

for t in l:
    print("Thread Name:", t.name)

enumerate() Concept

Currently Active Threads

MainThread
ChildThread1
ChildThread2
ChildThread3
       │
       ▼
   enumerate()
       │
       ▼
List of Active
Thread Objects
       │
       ▼
Loop Through List
       │
       ▼
Display Thread Names

Unlike active_count(), which gives only the number of active threads, enumerate() gives the actual Thread objects.

Program - enumerate()

🐍Code Cell
1from threading import *
2import time
3 
4def display():
5 print(current_thread().name, ".started")
6 time.sleep(3)
7 print(current_thread().name, ".ended")
8 
9t1 = Thread(target=display, name="ChildThread1")
10t2 = Thread(target=display, name="ChildThread2")
11t3 = Thread(target=display, name="ChildThread3")
12 
13t1.start()
14t2.start()
15t3.start()
16 
17l = enumerate()
18 
19for t in l:
20 print("Thread Name:", t.name)
21 
22time.sleep(5)
23 
24l = enumerate()
25 
26for t in l:
27 print("Thread Name:", t.name)
Output
No output captured.

Output - enumerate()

Program Explanation - enumerate()

Step 1: Import Required Modules

from threading import *
import time

The threading module provides thread-related functionality.

The time module is used for sleep().


Step 2: Create display() Function

def display():
    print(current_thread().name, ".started")
    time.sleep(3)
    print(current_thread().name, ".ended")

The function:

  1. Prints the current thread name with .started.
  2. Waits for 3 seconds.
  3. Prints the thread name with .ended.

Step 3: Create Three Child Threads

t1 = Thread(target=display, name="ChildThread1")
t2 = Thread(target=display, name="ChildThread2")
t3 = Thread(target=display, name="ChildThread3")

Three Child Threads are created.

Object Thread Name
t1 ChildThread1
t2 ChildThread2
t3 ChildThread3

Step 4: Start All Threads

t1.start()
t2.start()
t3.start()

All three Child Threads begin executing.


Step 5: Get All Active Threads

l = enumerate()

enumerate() returns a list containing all currently active threads.

At this point, normally the following four threads are active:

  1. MainThread
  2. ChildThread1
  3. ChildThread2
  4. ChildThread3

Step 6: Display Thread Names

for t in l:
    print("Thread Name:", t.name)

Each Thread object is taken from the list and its name property is displayed.

Therefore:

Thread Name: MainThread
Thread Name: ChildThread1
Thread Name: ChildThread2
Thread Name: ChildThread3

Step 7: Wait for Five Seconds

time.sleep(5)

The Main Thread waits for five seconds.

Each Child Thread waits only three seconds inside display().

Therefore, all Child Threads complete during this period.


Step 8: Call enumerate() Again

l = enumerate()

Now the Child Threads have completed.

Only:

MainThread

remains active.

Therefore, the second loop prints:

Thread Name: MainThread

Execution Flow - enumerate()

Program Starts
      │
      ▼
Create Three Threads
      │
      ▼
Start Threads
      │
      ▼
Child Threads Active
      │
      ▼
enumerate()
      │
      ▼
Returns All Active Threads
      │
      ▼
MainThread
ChildThread1
ChildThread2
ChildThread3
      │
      ▼
Display Thread Names
      │
      ▼
Main Thread Sleeps
for 5 Seconds
      │
      ▼
Child Threads Complete
      │
      ▼
enumerate()
      │
      ▼
Only MainThread
Remains Active

active_count() vs enumerate()

Function Returns Purpose
active_count() Integer Number of currently active threads
enumerate() List of Thread objects Actual currently active threads

Example:

active_count()
      │
      ▼
      4


enumerate()
      │
      ▼
[
 MainThread,
 ChildThread1,
 ChildThread2,
 ChildThread3
]

is_alive() Method

The is_alive() method checks whether a Thread is still executing or not.

Simple Definition:

is_alive() returns True if the Thread is still executing; otherwise, it returns False.

Syntax:

thread_object.is_alive()

Example:

t1.is_alive()

Possible results:

True  → Thread is still executing

False → Thread has completed execution

Program - is_alive()

🐍Code Cell
1from threading import *
2import time
3 
4def display():
5 print(current_thread().name, ".started")
6 time.sleep(3)
7 print(current_thread().name, ".ended")
8 
9t1 = Thread(target=display, name="ChildThread1")
10t2 = Thread(target=display, name="ChildThread2")
11 
12t1.start()
13t2.start()
14 
15print(t1.name, "is Alive :", t1.is_alive())
16print(t2.name, "is Alive :", t2.is_alive())
17 
18time.sleep(5)
19 
20print(t1.name, "is Alive :", t1.is_alive())
21print(t2.name, "is Alive :", t2.is_alive())
Output
No output captured.

Output - is_alive()

Program Explanation - is_alive()

Step 1: Create Two Child Threads

t1 = Thread(target=display, name="ChildThread1")
t2 = Thread(target=display, name="ChildThread2")

Two Child Thread objects are created.


Step 2: Start Both Threads

t1.start()
t2.start()

Both Child Threads begin executing display().

Inside display(), each Thread waits for three seconds.


Step 3: Check Whether Threads Are Alive

t1.is_alive()
t2.is_alive()

At this point, both Threads are still executing.

Therefore:

ChildThread1 is Alive : True
ChildThread2 is Alive : True

Step 4: Main Thread Waits Five Seconds

time.sleep(5)

The Main Thread waits for five seconds.

Both Child Threads need only about three seconds to complete.

Therefore, during these five seconds, both Child Threads finish.


Step 5: Check Again

t1.is_alive()
t2.is_alive()

Now both Threads have completed execution.

Therefore:

ChildThread1 is Alive : False
ChildThread2 is Alive : False

Execution Flow - is_alive()

Create Two Threads
      │
      ▼
Start Threads
      │
      ▼
Threads Are Executing
      │
      ▼
is_alive()
      │
      ▼
True
      │
      ▼
Main Thread
Waits 5 Seconds
      │
      ▼
Child Threads Complete
      │
      ▼
is_alive()
      │
      ▼
False

Modern Python Note - is_alive()

The source document uses:

is_alive()

The examples in this topic use the modern spelling is_alive():

print(t1.name, "is Alive :", t1.is_alive())
print(t2.name, "is Alive :", t2.is_alive())

The concept remains the same:

True  → Thread is alive

False → Thread is no longer alive

join() Method

If one Thread wants to wait until another Thread completes, we can use the join() method.

Simple Definition:

join() makes the calling Thread wait until the specified Thread completes its execution.

Syntax:

thread_object.join()

Example:

t.join()

If this statement is executed by the Main Thread:

Main Thread
     │
     ▼
t.join()
     │
     ▼
Wait for Thread t
     │
     ▼
Thread t Completes
     │
     ▼
Main Thread Continues

Why Do We Need join()?

Normally, after starting a Child Thread:

t.start()

the Main Thread continues executing independently.

Sometimes we want the Main Thread to continue only after the Child Thread finishes.

For that requirement, we use:

t.join()

Without join():

Main Thread ───────────────►

Child Thread ──────────────►

With join():

Main Thread
    │
    ▼
Start Child
    │
    ▼
join()
    │
    │ WAIT
    │
    ▼
Child Completes
    │
    ▼
Main Thread Continues

Program - join()

🐍Code Cell
1from threading import *
2import time
3 
4def display():
5 for i in range(10):
6 print("Seetha Thread")
7 time.sleep(2)
8 
9t = Thread(target=display)
10t.start()
11 
12t.join() # This line executed by Main Thread
13 
14for i in range(10):
15 print("Rama Thread")
Output
No output captured.

Output - join()

Program Explanation - join()

Step 1: Create display()

def display():
    for i in range(10):
        print("Seetha Thread")
        time.sleep(2)

The display() function is the job of the Child Thread.

It prints:

Seetha Thread

ten times.

After every print, it waits for two seconds.


Step 2: Create the Child Thread

t = Thread(target=display)

A Child Thread is created with display as its target.


Step 3: Start the Child Thread

t.start()

The Child Thread starts executing:

display()

Step 4: Main Thread Calls join()

t.join()

This statement is executed by the Main Thread.

Therefore, the Main Thread waits until Thread t completes.

Main Thread
    │
    ▼
t.join()
    │
    ▼
WAIT
    │
    ▼
Child Thread Executes
All 10 Iterations

Step 5: Child Thread Completes

The Child Thread prints:

Seetha Thread

ten times.

Only after the Child Thread finishes does join() return.


Step 6: Main Thread Continues

for i in range(10):
    print("Rama Thread")

Now the Main Thread resumes execution.

It prints:

Rama Thread

ten times.

Therefore, all Seetha Thread lines appear before the Rama Thread lines in this example.

Execution Flow - join()

Main Thread Starts
      │
      ▼
Create Child Thread
      │
      ▼
t.start()
      │
      ▼
Child Thread Starts
      │
      ├──────────────► display()
      │                    │
      │                    ▼
      │              Seetha Thread
      │
      ▼
Main Thread Calls
t.join()
      │
      ▼
Main Thread Waits
      │
      │
      │    Child Thread Continues
      │           │
      │           ▼
      │    Completes 10 Iterations
      │           │
      ◄───────────┘
      │
      ▼
join() Returns
      │
      ▼
Main Thread Continues
      │
      ▼
Print Rama Thread
10 Times

Without join() vs With join()

Without join() With join()
Main and Child Threads can continue concurrently. Calling Thread waits for the specified Thread.
Output may be interleaved. Following statements execute only after the joined Thread completes.
No explicit waiting for Child Thread. join() provides explicit waiting.

In the document's example:

WITHOUT join()

Seetha Thread
Rama Thread
Seetha Thread
Rama Thread
...

Order may vary.


WITH join()

Seetha Thread
Seetha Thread
...
10 times

Then

Rama Thread
Rama Thread
...
10 times

enumerate(), is_alive() and join() Comparison

Method / Function Purpose Return / Effect
enumerate() Find all active Threads Returns list of active Thread objects
is_alive() Check whether a Thread is executing True or False
join() Wait for another Thread to complete Blocks the calling Thread until completion

Thread Information and Management Methods Covered So Far

Method / Function Purpose
current_thread() Returns the currently executing Thread object
name Returns the Thread name
name = new_name Changes the Thread name
name Represents the Thread name
ident Provides the Thread identification number
active_count() Returns the number of active Threads
enumerate() Returns the list of active Threads
is_alive() Checks whether a Thread is executing
start() Starts a Thread
run() Contains the job performed by a Thread
join() Waits until the specified Thread completes

Summary

Topic Description
enumerate() Returns a list of all currently active Threads.
Initial enumerate() Example Returns MainThread and the three active Child Threads.
After Child Threads Finish Only MainThread remains in the list.
is_alive() Checks whether a Thread is still executing.
True The Thread is still alive/executing.
False The Thread has completed.
join() Makes the calling Thread wait for another Thread to complete.
join() Example Main Thread waits until all Seetha Thread output is completed before printing Rama Thread.

Important Notes

  1. enumerate() returns a list of all active Threads currently running.
  2. active_count() returns only the number of active Threads, whereas enumerate() returns the actual Thread objects.
  3. In the enumerate() example, initially MainThread and three Child Threads are active.
  4. After waiting five seconds, all three Child Threads complete and only MainThread remains active.
  5. is_alive() checks whether a Thread is still executing.
  6. is_alive() returns True when the Thread is executing.
  7. It returns False after the Thread has completed.
  8. The source document uses is_alive(); modern Python uses is_alive().
  9. join() is used when one Thread needs to wait until another Thread completes its execution.
  10. In the join() example, the Main Thread executes t.join().
  11. Therefore, the Main Thread waits until the Child Thread completes.
  12. The Child Thread prints Seetha Thread ten times before the Main Thread proceeds.
  13. After the Child Thread completes, the Main Thread prints Rama Thread ten times.
  14. join() is important when later statements depend on another Thread having completed.
📝 Key Takeaways
  • Every thread has a name, readable and changeable via the name property
  • ident gives each thread a unique identification number
  • active_count() returns how many threads are currently alive
  • enumerate() returns a list of all active thread objects
  • t.join() makes the calling thread wait until t finishes

🧠 Test Your Knowledge

27 Questions
Progress: 0 / 27