Python Thread - Is_alive Method

Method Name:

is_alive()

Method Overview:

is_alive() method checks whether a thread is alive and returns a boolean value based 
on the thread status.  is_alive() method is often used in thread synchronisation so as to
check whether a thread is alive before sending any signals to it. However efforts need to be
taken to have status of the latest thread status from a most recent call to  is_alive().

Return value:

True    - When a thread is alive
False   - When a thread has been already terminated completely.

Example:

from threading import Thread;

from threading import Event;

import time;

 

class ChildThread(Thread):

    myStopSignal = 0

   

    def __init__(self,aStopSignal):

        Thread.__init__(self)

        self.myStopSignal = aStopSignal   

       

    def run(self):

        print("Child Thread:Started")

        for i in range(1,10):

            if(self.myStopSignal.wait(0)):

                print ("ChildThread:Asked to stop")

                break;       

 

            print("Doing some low priority task taking long time")

            time.sleep(2) #Just simulating time taken by task with sleep

 

        print("Child Thread:Exiting")

 

print("Main Thread:Started")

aStopSignal     = Event()           

aChildThread    = ChildThread(aStopSignal)

aChildThread.start()

aChildThread.join(4) # I can wait for 4 seconds only

 

if aChildThread.is_alive() is True:

    aStopSignal.set()

    aChildThread.join()

 

print("Main Thread; Exiting")

 

Output:

pythoncomputer:PythonExamples pythonuser$ python is_alive_example.py

Main Thread:Started

Child Thread:Started

Doing some low priority task taking long time

Doing some low priority task taking long time

ChildThread:Asked to stop

Child Thread:Exiting

Main Thread; Exiting


 


Copyright 2023 © pythontic.com