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
In Python, the method threading. active_co unt() from the threading module is used to count the currently active or running threads.
The isAlive() method of thread class tests if the thread is alive. A thread is considered alive when the start() method of thread class has been called and the thread is not yet dead. This method returns true if the thread is still running and not finished.
This can be achieved by creating a new thread instance and using the “target” argument to specify the watchdog function. The watchdog can be given an appropriate name, like “Watchdog” and be configured to be a daemon thread by setting the “daemon” argument to True.
In Python, you simply cannot kill a Thread directly. If you do NOT really need to have a Thread (!), what you can do, instead of using the threading package , is to use the multiprocessing package . Here, to kill a process, you can simply call the method: yourProcess.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With