I would like to run different functions in parallel (foo, bar, and baz), and then get the value returned by each function in the order in which they were called.
I tried something like the code below, but fore some reason it loops forever on Windows. Is it possible to achieve this using for example multiprocessing
? Note that the functions are expected to take as parameter the same thing (i.e. data).
Note: The code below is for Python 3, I want an equivalent for Python 2.7 as it is what I need to use.
from concurrent.futures import ProcessPoolExecutor
from operator import itemgetter
def foo(data):
return "foo"
def bar(data):
return "bar"
def baz(data):
return "baz"
work = [foo, bar, baz]
data = [1,2,3,4,5]
results = []
with ProcessPoolExecutor(max_workers=4) as pool:
for i, work_item in enumerate(work):
future = pool.submit(work_item, data)
def callback(ret):
results.append((i, ret.result()))
future.add_done_callback(callback)
results.sort(key=itemgetter(0))
print(results)