Alpesh Valaki
Alpesh Valaki

Reputation: 1631

How to get thread status from ID (integer)?

I have one method which is call using thread.

I have stored thread id using following code into database.

t1 = Thread(target=task_1)
thread = t1.start()
thread_id = t1.ident # i will store this id in database for future use.

Lets say i stored thread_id : 6184169472 in database

Now lets say after 3 or 4 hours i want to check status of stored thread ID (6184169472)

How can i check that this thread is still running or not using ID?

Upvotes: 0

Views: 203

Answers (1)

Danil Perestoronin
Danil Perestoronin

Reputation: 1153

As far as I know, the threading module does not provide any functions for checking is thread still alive by id.

But, as a workaround, you can get a list of all active Threads by threading.enumerate()

Return a list of all Thread objects currently active.

And then check if this list contains Thread with stored id. If yes - the thread still running.

As example:

import random
import threading


def is_alive(ident):
    return any(th.ident == ident for th in threading.enumerate())


t_ident = threading.current_thread().ident  # get current thread ident
print("Is current thread still alive: ", is_alive(t_ident))  # True

r_ident = random.randrange(1000)
print("Is thread with random indent still alive: ", is_alive(r_ident))  # False

Upvotes: 1

Related Questions