Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: is thread still running

Tags:

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 
like image 258
user984003 Avatar asked Feb 25 '13 09:02

user984003


People also ask

How do I check if a Python thread is running?

In Python, the method threading. active_co unt() from the threading module is used to count the currently active or running threads.

How do you check if a thread is still running?

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.

How do I monitor a thread in Python?

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.

How do you stop a thread from running in Python?

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.


2 Answers

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. 
like image 132
user984003 Avatar answered Oct 19 '22 08:10

user984003


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

like image 22
Kunal Raut Avatar answered Oct 19 '22 08:10

Kunal Raut