Checking on a thread / remove from list

前端 未结 5 566
无人及你
无人及你 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:50
    mythreads = threading.enumerate()
    

    Enumerate returns a list of all Thread objects still alive. https://docs.python.org/3.6/library/threading.html

    0 讨论(0)
  • 2020-12-13 19:54

    Better way is to use Queue class: http://docs.python.org/library/queue.html

    Look at the good example code in the bottom of documentation page:

    def worker():
        while True:
            item = q.get()
            do_work(item)
            q.task_done()
    
    q = Queue()
    for i in range(num_worker_threads):
         t = Thread(target=worker)
         t.daemon = True
         t.start()
    
    for item in source():
        q.put(item)
    
    q.join()       # block until all tasks are done
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 20:04

    The answer has been covered, but for simplicity...

    # To filter out finished threads
    threads = [t for t in threads if t.is_alive()]
    
    # Same thing but for QThreads (if you are using PyQt)
    threads = [t for t in threads if t.isRunning()]
    
    0 讨论(0)
  • 2020-12-13 20:17

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

    0 讨论(0)
提交回复
热议问题