python - 在 Python 中将多个参数传递给 pool.map() 函数

标签 python multiprocessing pool map-function

我需要一些方法来使用 pool.map() 中接受多个参数的函数。根据我的理解, pool.map() 的目标函数只能有一个可迭代的参数,但有没有办法可以传递其他参数?在这种情况下,我需要传入一些配置变量,例如我的 Lock() 和日志信息到目标函数。

我试图做一些研究,我认为我可以使用部分函数来让它工作?但是我不完全理解这些是如何工作的。任何帮助将不胜感激!这是我想做的一个简单示例:

def target(items, lock):
    for item in items:
        # Do cool stuff
        if (... some condition here ...):
            lock.acquire()
            # Write to stdout or logfile, etc.
            lock.release()

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    pool.map(target(PASS PARAMS HERE), iterable)
    pool.close()
    pool.join()

最佳答案

您可以使用 functools.partial为此(正如您所怀疑的):

from functools import partial

def target(lock, iterable_item):
    for item in iterable_item:
        # Do cool stuff
        if (... some condition here ...):
            lock.acquire()
            # Write to stdout or logfile, etc.
            lock.release()

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    l = multiprocessing.Lock()
    func = partial(target, l)
    pool.map(func, iterable)
    pool.close()
    pool.join()

例子:

def f(a, b, c):
    print("{} {} {}".format(a, b, c))

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    a = "hi"
    b = "there"
    func = partial(f, a, b)
    pool.map(func, iterable)
    pool.close()
    pool.join()

if __name__ == "__main__":
    main()

输出:

hi there 1
hi there 2
hi there 3
hi there 4
hi there 5

关于python - 在 Python 中将多个参数传递给 pool.map() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25553919/

相关文章:

Python 多线程与共享变量

python - 如何使用带有 Mutliprocessing 的 PYTHON 打开程序,并从主进程向其发送字符串?

java - 如何创建对象池以能够借用和归还对象

Python 多处理 : how to limit the number of waiting processes?

python - 为什么 ctrl+c 必须是导致错误的组合(例如 KeyboardInterrupt)?

python - 使用 urllib2 从 FlightRadar24 获取数据时出现问题

python - python moviepy中的多处理

java - 关于对象池的问题

python - 非序列化数据的共享内存缓存

python - 创建空字典列表