Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking on a thread / remove from list

I have a thread which extends Thread. The code looks a little like this;

class MyThread(Thread):     def run(self):         # Do stuff  my_threads = [] while has_jobs() and len(my_threads) < 5:     new_thread = MyThread(next_job_details())     new_thread.run()     my_threads.append(new_thread)  for my_thread in my_threads     my_thread.join()     # Do stuff 

So here in my pseudo code I check to see if there is any jobs (like a db etc) and if there is some jobs, and if there is less than 5 threads running, create new threads.

So from here, I then check over my threads and this is where I get stuck, I can use .join() but my understanding is that - this then waits until it's finished so if the first thread it checks is still in progress, it then waits till it's done - even if the other threads are finished....

so is there a way to check if a thread is done, then remove it if so?

eg

for my_thread in my_threads:     if my_thread.done():         # process results         del (my_threads[my_thread]) ?? will that work... 
like image 368
Wizzard Avatar asked Nov 01 '10 09:11

Wizzard


People also ask

How do I check thread status in Python?

is_alive() method is an inbuilt method of the Thread class of the threading module in Python. It uses a Thread object, and checks whether that thread is alive or not, ie, it is still running or not. This method returns True before the run() starts until just after the run() method is executed.

How do you check active threads in Python?

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

What is the method to retrieve the list of all active threads?

enumerate() returns a list of all Thread objects currently alive. The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread.

How do you stop a blocking thread in Python?

sleep(0.1) if __name__ == "__main__": thread = BlockingTestThread() thread. start() _async_raise(thread. ident, SystemExit) print "Joining thread" thread. join() print "Done Joining thread" #will never get here!


2 Answers

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:     if not t.is_alive():         # get results from thread         t.handled = True my_threads = [t for t in my_threads if not t.handled] 

This avoids the problem of removing items from a list while iterating over it.

like image 143
Arlaharen Avatar answered Sep 24 '22 02:09

Arlaharen


you need to call thread.isAlive()to find out if the thread is still running

like image 33
SingleNegationElimination Avatar answered Sep 23 '22 02:09

SingleNegationElimination