python多进程multiprocessing Pool相关问题

python多进程想必大部分人都用到过,可以充分利用多核CPU让代码效率更高效。

我们看看multiprocessing.pool.Pool.map的官方用法

map(func, iterable[, chunksize])
A parallel equivalent of the map() built-in function (it supports only one iterable argument though). It blocks until the result is ready.

This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. The (approximate) size of these chunks can be specified by setting chunksize to a positive integer.

一、多参数传入如何变成一个参数

map的用法,函数func只允许一个可迭代的参数传递进去。

如果我们需要传递多个参数时怎么办呢,

一种方法是把多个参数放入到一个list或者元祖里当做一个参数传入func中

还有一种是使用偏函数,偏函数(Partial function)是通过将一个函数的部分参数预先绑定为某些值,从而得到一个新的具有较少可变参数的函数。在Python中,可以通过functools中的partial高阶函数来实现偏函数功能。偏函数partial的源码如下:

def partial(func, *args, **keywords):
    """New function with partial application of the given arguments
    and keywords.
    """
    if hasattr(func, 'func'):
        args = func.args + args
        tmpkw = func.keywords.copy()
        tmpkw.update(keywords)
        keywords = tmpkw
        del tmpkw
        func = func.func

    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

使用方法也很简单,比如我们有一个func函数,里面要传入texts,lock, data三个参数,但是我们想要用多进程把data分别传入进去计算,那么我们就可以先用partial函数,将texts和lock先固定到函数里组成一个新的函数,然后新函数传入data一个参数就可以了

from functools import partial
def func(texts, lock, data):
    ......


pt = partial(func, tests, lock)  

# 新函数pt只需要传入一个参数data

这我们就可以对pt函数套用pool.map函数并且只传入一个参数data里。

二、多进程间通讯

还有一种情况是,多进程间要相互之间通讯,比如我每一个进程的结果都要存入到texts这个list里。当然要把这个texts当做参数传入到函数里面,但是一般的list并不能共享给所有的进程,我们需要用multiprocessing.Manager().list()建立的list才可以用于进程间通讯,防止冲突,还要对texts加上锁,防止操作冲突。注意multiprocessing.Lock() 创建的锁不能传递,需要使用multiprocessing.Manager().Lock()来创建。multiprocessing.Manager()可创建字典,也可创建list,lock,它创建的变量可用于多进程间传递才不会出错。比如以下代码:

texts = multiprocessing.Manager().list()
lock = multiprocessing.Manager().Lock()
pool = multiprocessing.Pool(processes=4)
data = list(range(20))
pt = partial(func, texts, lock)
pool.map(pt, data)
pool.close()
pool.join()

猜你喜欢

转载自www.cnblogs.com/zongfa/p/11332556.html