19
votes

How do I see whether a thread has completed? I tried the following, but threads_list does not contain the thread that was started, even when I know the thread is still running.

import thread
import threading

id1 = thread.start_new_thread(my_function, ())
#wait some time
threads_list = threading.enumerate()
# Want to know if my_function() that was called by thread id1 has returned 

def my_function()
    #do stuff
    return
3

3 Answers

38
votes

The key is to start the thread using threading, not thread:

t1 = threading.Thread(target=my_function, args=())
t1.start()

Then use

z = t1.is_alive()
# Changed from t1.isAlive() based on comment. I guess it would depend on your version.

or

l = threading.enumerate()

You can also use join():

t1 = threading.Thread(target=my_function, args=())
t1.start()
t1.join()
# Will only get to here once t1 has returned.
1
votes

You must start the thread by using threading.

id1 = threading.Thread(target = my_function)
id1.start()

And as of above if you don't have any args to mention you can just leave it blank.

To check your thread is alive or not you can use is_alive()

if id1.is_alive():
   print("Is Alive")
else:
   print("Dead")

Note: isAlive() is deprecated instead use is_alive()as per the python docs.

Python Documentation

-1
votes

This is my code, It's not exactly what you asked, but maybe you will find it useful

import time
import logging
import threading

def isTreadAlive():
  for t in threads:
    if t.isAlive():
      return 1
  return 0


# main loop for all object in Array 

threads = []

logging.info('**************START**************')

for object in Array:
  t= threading.Thread(target=my_function,args=(object,))
  threads.append(t)
  t.start()

flag =1
while (flag):
  time.sleep(0.5)
  flag = isTreadAlive()

logging.info('**************END**************')