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

时间:2018-12-09 19:55:29

标签: python python-3.x multithreading python-2.7 python-multithreading

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

  

这里的问题是我该如何真正确定我的程序是否对self.boxes队列中的所有元素执行线程并返回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")

1 个答案:

答案 0 :(得分:3)

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

方法:

  • 用类常量替换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
    

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

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