代码之家  ›  专栏  ›  技术社区  ›  Arbazz Hussain

如何识别带有队列的python线程是否完成了任务?

  •  2
  • Arbazz Hussain  · 技术社区  · 6 年前

    我来了 MazeRunner 类的所有元素 self.boxes 在队列中运行线程,直到所有队列变为空 q.empty() .

    这里的问题是,我如何真正地确定我的程序是否在队列中的所有元素上执行线程 自带盒 返回 True .

    看起来很有挑战性,因为 our threads 处于while循环中,该循环根据 自带盒 长度和长度; 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")
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   RomanPerekhrest    6 年前

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

    如何:

    • 取代你 self.threads = 5 具有类常量的表达式:

      THREAD_NUM = 5
      
    • 添加附加属性 threads (用于线程列表)进入 __init__ 方法:

      ...
      self.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
      

    您需要检查“全部完成”的方式:

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