Python Thread is_alive() Method with Example

In Python’s `threading` module, the `is_alive()` method is used to check whether a thread is currently active and running. Here’s an explanation of how to use `is_alive()` with an example

In python threading module the is_alive()

E

import threading
import time

def thread_function():
    print("Thread is running...")
    time.sleep(2)
    print("Thread is exiting...")
threading.Thread(target=thread_function)
thread.start()
if thread.is_alive():
    print("Thread is active.")
else:
    print("Thread is not active.")
thread.join()
if thread.is_alive():
    print("Thread is still active after joining.")
else:
    print("Thread has completed and is not active.")

Output 
Thread is running
Thread is active
Thread is execute
Thread is active not complete 




 

Explanation

1. **Defining the Thread Function**:

   – `thread_function()` is a simple function that prints messages and then sleeps for 2 seconds.

2. **Creating a Thread**:

   – `thread = threading.Thread(target=thread_function)` creates a `Thread` object named `thread`, targeting the `thread_function` as its execution target.

3. **Starting the Thread**:

   – `thread.start()` initiates the execution of the thread by invoking the `thread_function()`.

4. **Checking if the Thread is Alive**:

   – `thread.is_alive()` is used to check if the thread is currently active and running. Initially, it will return `True` because the thread has been started but not yet completed.

5. **Joining the Thread**:

   – `thread.join()` is called to wait for the thread to complete its execution. This ensures that the main program waits until the thread finishes before proceeding.

6. **Re-checking if the Thread is Alive**:

   – After joining, `thread.is_alive()` is checked again. Now, it should return `False` because the thread has completed its execution.

When you run the above code, the expected output will be:

Thread is running…

Thread is active.

Thread is exiting…

Thread has completed and is not active.

Summary

`is_alive()` is a method available on `Thread` objects in Python’s `threading` module.

– It returns `True` if the thread is currently executing and `False` otherwise.

– Use `is_alive()` to dynamically check the status of a thread during its lifecycle, such as before and after joining to determine if it’s still active or has completed.


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top