Remis Haroon - رامز
Remis Haroon - رامز

Reputation: 3572

python: Check status of thread by ID

I have a multithreading Python(2.7) program, which runs multiple threads for different tasks. I am storing the thread-ids, for tracking the status of threads in a separate thread for status-tracking.

How can I check the thread is alive or not ( isAlive() ) by having the thread-id ?

Upvotes: 1

Views: 1863

Answers (2)

Danil Perestoronin
Danil Perestoronin

Reputation: 1153

You can get a list of all active Threads by threading.enumerate() (for Python 3: 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 is still alive.

As example:

import threading

t_id = 1080 # stored thread id
is_alive = any([th for th in threading.enumerate() if th.ident == t_id])

print("Still alive: ", is_alive)

Upvotes: 2

junnytony
junnytony

Reputation: 3515

As far as I know, I don't believe there's a way to retrieve the thread by its thread_id. Your best bet would be to store a reference to the thread object itself.

Upvotes: 1

Related Questions