Python, ThreadPoolExecutor,池执行不终止



我有我简单的代码建模一个更复杂的问题,我要解决。这里我有3个函数- worker,任务提交者(查找任务并在获得新任务后将其放入队列)和创建池并向此池添加新任务的函数。但是,在队列变为空并且列表中的所有任务都完成后,代码不会完成运行。我太转储有一个想法,为什么地狱它不终止While循环与条件…我已经尝试了不同的方法来编码的东西,没有工作

from concurrent.futures import ThreadPoolExecutor as Tpe
import time
import random
import queue
import threading

def task_submit(q):
for i in range(7):
threading.currentThread().setName('task_submit')
new_task = random.randint(10, 20)
q.put_nowait(new_task)
print(f'                                {i} new task with argument {new_task} has been added to queue')
time.sleep(5)

def worker(t):
threading.currentThread().setName(f'worker {t}')
print(f'{threading.currentThread().getName()} started')
time.sleep(t)
print(f'{threading.currentThread().getName()} FINISHED!')

def execution():
executor = Tpe(max_workers=4)
q = queue.Queue(maxsize=100)
q_thread = executor.submit(task_submit, q)
tasks = [executor.submit(worker, q.get())]
execution_finished = False
while not execution_finished:                           #all([task.done() for task in tasks]):
if not all([task.done() for task in tasks]):
print('             still in progress .....................')
tasks.append(executor.submit(worker, q.get()))
else:
print('             all done!')
executor.shutdown()
execution_finished = True

execution()

它不会因为您试图从空队列中删除项目而终止。问题在这里:

while not execution_finished:                           
if not all([task.done() for task in tasks]):
print('             still in progress .....................')
tasks.append(executor.submit(worker, q.get()))

这里的最后一行向执行者提交了一个新的工作项。假设这恰好是队列中的最后一项。此时,执行器还没有完成,几秒钟后才会完成。主线程返回到while not execution_finished行,并且if语句的计算结果为true,因为有些任务仍在运行。所以你尝试再提交一个项目,但你不能,因为队列现在是空的。对q.get的调用阻塞了主循环,直到队列包含一个项目,这永远不会发生。由于主线程被阻塞,其他线程结束,但程序没有退出。

也许你应该检查空队列,但我不确定这是正确的主意,因为我可能不理解你的要求。在任何情况下,这就是为什么你的脚本不退出。

最新更新