How does ThreadPoolExecutor().map differ from ThreadPoolExecutor().submit? How does ThreadPoolExecutor().map differ from ThreadPoolExecutor().submit? multithreading multithreading

How does ThreadPoolExecutor().map differ from ThreadPoolExecutor().submit?


The problem is that you transform the result of ThreadPoolExecutor.map to a list. If you don't do this and instead iterate over the resulting generator directly, the results are still yielded in the original order but the loop continues before all results are ready. You can test this with this example:

import timeimport concurrent.futurese = concurrent.futures.ThreadPoolExecutor(4)s = range(10)for i in e.map(time.sleep, s):    print(i)

The reason for the order being kept may be because it's sometimes important that you get results in the same order you give them to map. And results are probably not wrapped in future objects because in some situations it may take just too long to do another map over the list to get all results if you need them. And after all in most cases it's very likely that the next value is ready before the loop processed the first value. This is demonstrated in this example:

import concurrent.futuresexecutor = concurrent.futures.ThreadPoolExecutor() # Or ProcessPoolExecutordata = some_huge_list()results = executor.map(crunch_number, data)finals = []for value in results:    finals.append(do_some_stuff(value))

In this example it may be likely that do_some_stuff takes longer than crunch_number and if this is really the case it's really not a big loss of performance while you still keep the easy usage of map.

Also since the worker threads(/processes) start processing at the beginning of the list and work their way to the end to the list you submitted the results should be finished in the order they're already yielded by the iterator. Which means in most cases executor.map is just fine, but in some cases, for example if it doesn't matter in which order you process the values and the function you passed to map takes very different times to run, the future.as_completed may be faster.


if you use concurrent.futures.as_completed, you can handle the exception for each function.

import concurrent.futuresiterable = [1,2,3,4,6,7,8,9,10]def f(x):    if x == 2:        raise Exception('x')    return xwith concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:    result_futures = list(map(lambda x: executor.submit(f, x), iterable))    for future in concurrent.futures.as_completed(result_futures):        try:            print('resutl is', future.result())        except Exception as e:            print('e is', e, type(e))# resutl is 3# resutl is 1# resutl is 4# e is x <class 'Exception'># resutl is 6# resutl is 7# resutl is 8# resutl is 9# resutl is 10

in executor.map, if there is an exception, the whole executor would stop. you need to handle the exception in the worker function.

with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:    for each in executor.map(f, iterable):        print(each)# if there is any exception, executor.map would stop


In addition to the explanation in the answers here, it can be helpful to go right to the source. It reaffirms the statement from another answer here that:

  • .map() gives results in the order they are submitted, while
  • iterating over a list of Future objects with concurrent.futures.as_completed() won't guarantee this ordering, because this is the nature of as_completed()

.map() is defined in the base class, concurrent.futures._base.Executor:

class Executor(object):    def submit(self, fn, *args, **kwargs):        raise NotImplementedError()    def map(self, fn, *iterables, timeout=None, chunksize=1):        if timeout is not None:            end_time = timeout + time.monotonic()        fs = [self.submit(fn, *args) for args in zip(*iterables)]  # <!!!!!!!!        def result_iterator():            try:                # reverse to keep finishing order                fs.reverse()  # <!!!!!!!!                while fs:                    # Careful not to keep a reference to the popped future                    if timeout is None:                        yield fs.pop().result()  # <!!!!!!!!                    else:                        yield fs.pop().result(end_time - time.monotonic())            finally:                for future in fs:                    future.cancel()        return result_iterator()

As you mention, there is also .submit(), which left to be defined in the child classes, namely ProcessPoolExecutor and ThreadPoolExecutor, and returns a _base.Future instance that you need to call .result() on to actually make do anything.

The important lines from .map() boil down to:

fs = [self.submit(fn, *args) for args in zip(*iterables)]fs.reverse()while fs:    yield fs.pop().result()

The .reverse() plus .pop() is a means to get the first-submitted result (from iterables) to be yielded first, the second-submitted result to be yielded second, and so on. The elements of the resulting iterator are not Futures; they're the actual results themselves.