Py3 ThreadPoolExecutor: как получить количество оставшихся элементов до выполнения - PullRequest
0 голосов
/ 16 апреля 2020

Я пытаюсь добавить несколько длительных потоков в ThreadPool в Python3. Для каждого потока, как я могу определить, сколько задач находится перед ним, прежде чем он будет выполнен?

Моя цель - показать пользователю "У вас есть X элементов, ожидающих до вашей задачи". Это не проблема, если он не точен, когда достигает max_workers.

with futures.ThreadPoolExecutor(max_workers=2) as executor:
  future1 = executor.submit(task, 10) 
  future2 = executor.submit(task, 10)
  future3 = executor.submit(task, 10)

 # my naive failed attempt was
 numOfRemainingTasks = (len(executor)-1) - executor.indexof(future3)

1 Ответ

1 голос
/ 16 апреля 2020

Если я правильно понимаю, вы хотите что-то в этом роде?

import concurrent.futures

class CustomExecutor(concurrent.futures.ThreadPoolExecutor):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    def submit(self, *args, **kwargs):
        print(f'There are {self._work_queue.qsize()} items in front of me')
        return super().submit(*args, **kwargs)

def task(num):
    return num + 10


with CustomExecutor(max_workers=2) as executor:
    futures = (executor.submit(task, 10) for _ in range(6))
    for future in concurrent.futures.as_completed(futures):
        print(future.result())

There are 0 items in front of me
There are 0 items in front of me
There are 0 items in front of me
There are 1 items in front of me
There are 1 items in front of me
There are 2 items in front of me
....
...