Checking on a thread / remove from list

前端 未结 5 596
无人及你
无人及你 2020-12-13 19:19

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         


        
5条回答
  •  隐瞒了意图╮
    2020-12-13 19:59

    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.

提交回复
热议问题