如何确定 Python 个带有队列的线程是否已完成任务?

How to identify if Python Threads with Queue are done with task?

这里我有 MazeRunner Class 将 self.boxes 的所有元素放入队列并 运行 在它们上面线程化,直到所有队列都变空 q.empty().

Here problem is how do i actually identify if my program is done performing threads on all elements which are in queue of self.boxes & return True.

它看起来很有挑战性,因为 our threads 处于 while 循环中,它根据我们定义的 self.boxes 长度和 self.threads 保持变化。 我已经尝试将所有线程放入列表中并 t.join 全部。但不是运气。有帮助吗?

import threading,queue,time 

class MazeRunner:
    def __init__(self):
        self.q = queue.Queue()
        self.boxes = [1,2,3,4,5,6,7] ## `7` elements of list
        self.threads = 5

        for i in self.boxes:
            self.q.put(i) ### ADDING Every element of list to queue

        for j in range(self.threads): ### for i in range(5)  threads
            t = threading.Thread(target=self.ProcessQueue)
            t.start() ### Started `5` threads on `7` elements

    def ProcessQueue(self):
        while not self.q.empty():
            each_element = self.q.get()
            self.SleepFunction(each_element)
            self.q.task_done()

    def SleepFunction(self,each_element):
        print("STARTING : ",each_element)
        time.sleep(10)
        print("DONE : ",each_element)

lets_try = MazeRunner()
if lets_try == True:
     print("All Threads Done on Elements")

您需要等到所有线程都完成调用 Thread.join:

HOWTO:

  • 用 class 常量替换您的 self.threads = 5 表达式:

    THREAD_NUM = 5
    
  • 将附加属性 threads(用于线程列表)放入您的 __init__ 方法中:

    ...
    self.threads = []
    
  • 将每个创建的线程放入threads列表:

    for j in range(self.THREAD_NUM):
        t = threading.Thread(target=self.ProcessQueue)
        self.threads.append(t)
        t.start()
    
  • 定义类似check_completed的方法以确保所有线程都被终止(完成):

    ....
    
    def check_completed(self):
        for t in self.threads:
            t.join()
        return True
    

您需要检查的方式"all done":

m_runner = MazeRunner()
if m_runner.check_completed():
    print("All Threads Done on Elements")