在这里,我有一个MazeRunner类,它将所有元素self.boxes放入队列并在它们上运行线程,直到所有队列变空q.empty()。这里的问题是我如何实际确定我的程序是否已完成对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")
1 回答
肥皂起泡泡
TA贡献1829条经验 获得超6个赞
您需要等到所有线程都完成调用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")
添加回答
举报
0/150
提交
取消