Python,使用初始化启动concurrent.futures.ProcessPoolExecutor?

时间:2015-08-21 01:27:47

标签: python python-3.x concurrency multiprocessing subprocess

我计划使用concurrent.futures.ProcessPoolExecutor来并行执行功能。根据{{​​3}},其executor对象只能接受map中的简单函数。我的实际情况涉及在执行“待并行化”之前初始化(加载数据)。功能。我该如何安排?

待并行化的'函数在迭代中被多次调用。我不希望每次都重新初始化它。

换句话说,有一个init函数可以为这个tbp函数产生一些输出。每个孩子都应该拥有自己的输出副本,因为这个功能取决于它。

2 个答案:

答案 0 :(得分:5)

听起来您正在寻找与multiprocessing.Pool所采用的initializer / initargs选项等价的内容。目前,concurrent.futures.ProcessPoolExecutor的行为并不存在,尽管有patch waiting for review可以添加该行为。

因此,您可以使用multiprocessing.Pool(这可能适用于您的用例),等待该补丁进行合并和释放(您可能需要等待一段时间:)),或者滚动您自己的解决方案。事实证明,编写一个包含initializer的地图的包装函数并不难,但每个进程只调用一个:

from concurrent.futures import ProcessPoolExecutor
from functools import partial

inited = False
initresult = None

def initwrapper(initfunc, initargs, f, x):
    # This will be called in the child. inited
    # Will be False the first time its called, but then
    # remain True every other time its called in a given
    # worker process.
    global inited, initresult
    if not inited:
        inited = True
        initresult = initfunc(*initargs)
    return f(x)

def do_init(a,b):
    print('ran init {} {}'.format(a,b))
    return os.getpid() # Just to demonstrate it will be unique per process

def f(x):
    print("Hey there {}".format(x))
    print('initresult is {}'.format(initresult))
    return x+1

def initmap(executor, initializer, initargs, f, it):
    return executor.map(partial(initwrapper, initializer, initargs, f), it)


if __name__ == "__main__":
    with ProcessPoolExecutor(4) as executor:
        out = initmap(executor, do_init, (5,6), f, range(10))
    print(list(out))

输出:

ran init 5 6
Hey there 0
initresult is 4568
ran init 5 6
Hey there 1
initresult is 4569
ran init 5 6
Hey there 2
initresult is 4570
Hey there 3
initresult is 4569
Hey there 4
initresult is 4568
ran init 5 6
Hey there 5
initresult is 4571
Hey there 6
initresult is 4570
Hey there 7
initresult is 4569
Hey there 8
initresult is 4568
Hey there 9
initresult is 4570
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

答案 1 :(得分:1)

Python 3.7开始,ThreadPoolExecutorProcessPoolExecutor都具有可选的initializerinitargs参数。每个线程/进程在启动后都会调用initializer(*initargs)

请参见https://docs.python.org/3.7/library/concurrent.futures.html