如何模仿多处理.Pool.map()在AWS Lambda?

2024-06-02 16:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

AWS Lambda上的Python不支持multiprocessing.Pool.map(),如this other question中所述。请注意,另一个问题是问它为什么不起作用。这个问题不同,我要问的是,在缺乏底层支持的情况下,如何模拟功能。在

另一个问题的答案给了我们这样一个代码:

# Python 3.6
from multiprocessing import Pipe, Process

def myWorkFunc(data, connection):
    result = None

    # Do some work and store it in result

    if result:
        connection.send([result])
    else:
        connection.send([None])


def myPipedMultiProcessFunc():

    # Get number of available logical cores
    plimit = multiprocessing.cpu_count()

    # Setup management variables
    results = []
    parent_conns = []
    processes = []
    pcount = 0
    pactive = []
    i = 0

    for data in iterable:
        # Create the pipe for parent-child process communication
        parent_conn, child_conn = Pipe()
        # create the process, pass data to be operated on and connection
        process = Process(target=myWorkFunc, args=(data, child_conn,))
        parent_conns.append(parent_conn)
        process.start()
        pcount += 1

        if pcount == plimit: # There is not currently room for another process
            # Wait until there are results in the Pipes
            finishedConns = multiprocessing.connection.wait(parent_conns)
            # Collect the results and remove the connection as processing
            # the connection again will lead to errors
            for conn in finishedConns:
                results.append(conn.recv()[0])
                parent_conns.remove(conn)
                # Decrement pcount so we can add a new process
                pcount -= 1

    # Ensure all remaining active processes have their results collected
    for conn in parent_conns:
        results.append(conn.recv()[0])
        conn.close()

    # Process results as needed

能否修改此示例代码以支持multiprocessing.Pool.map()?在

到目前为止,我做了什么

我分析了上面的代码,但没有看到要执行的函数或数据的参数,因此我推断它与multiprocessing.Pool.map()执行的功能不同。除了演示可以组装成解决方案的构建块之外,还不清楚代码的作用。在

这是一个“为我写代码”的问题吗?

在某种程度上是的。这个问题影响了成千上万的Python开发人员,如果我们共享同一个代码,而不是强迫每个遇到这个问题的用户去开发他们自己的解决方案,那么对于世界经济来说,效率会更高,温室气体排放更少等等。我希望我已经尽了我的职责,把这个问题提炼成一个明确的问题,假设构建块已经准备好了。在


Tags: the代码infordataresultconnectionconn
1条回答
网友
1楼 · 发布于 2024-06-02 16:57:25

我能让它为我自己的测试工作。 我的代码基于这个链接:https://aws.amazon.com/blogs/compute/parallel-processing-in-python-with-aws-lambda/

NB1:必须增加lambda函数的内存分配。使用默认的最小数量,多处理不会提高性能。随着我的帐户可以分配的最大值(3008MB),下面的数字达到了。在

NB2:我完全忽略了并行的max进程。我的用法没有太多的元素需要处理。在

使用下面的代码,用法是:

work = funcmap(yourfunction,listofstufftoworkon)
yourresults = work.run()

从我的笔记本电脑上运行:

^{pr2}$

从aws运行:

Function Logs:
START RequestId: 075a92c0-7c4f-4f48-9820-f394ee899a97 Version: $LATEST
results : [(35, 9227465), (35, 9227465), (35, 9227465), (35, 9227465)]
SP runtime : 12.135798215866089
results : [(35, 9227465), (35, 9227465), (35, 9227465), (35, 9227465)]
MP runtime : 7.293526887893677
END RequestId: 075a92c0-7c4f-4f48-9820-f394ee899a97

测试代码如下:

import time
from multiprocessing import Process, Pipe
import boto3

class funcmap(object):

    fmfunction=None
    fmlist=None

    def __init__(self,pfunction,plist):
        self.fmfunction=pfunction
        self.fmlist=plist

    def calculation(self, pfunction, pload, conn):
        panswer=pfunction(pload)
        conn.send([pload,panswer])
        conn.close()

    def run(self):
        datalist = self.fmlist
        processes = []
        parent_connections = []
        for datum in datalist:
            parent_conn, child_conn = Pipe()
            parent_connections.append(parent_conn)
            process = Process(target=self.calculation, args=(self.fmfunction, datum, child_conn,))
            processes.append(process)

        pstart=time.time()
        for process in processes:
            process.start()
            #print("starting at t+ {} s".format(time.time()-pstart))
        for process in processes:
            process.join()
            #print("joining at t+ {} s".format(time.time()-pstart))

        results = []
        for parent_connection in parent_connections:
            resp=parent_connection.recv()
            results.append((resp[0],resp[1]))
        return results


def fibo(n):
    if n <= 2 : return 1
    return fibo(n-1)+fibo(n-2)

def lambda_handler(event, context):
    #worklist=[22,23,24,25,26,27,28,29,30,31,32,31,30,29,28,27,26,27,28,29]
    #worklist=[22,23,24,25,26,27,28,29,30]
    worklist=[30,30,30,30]
    #worklist=[30]
    _start = time.time()
    results=[]
    for a in worklist:
        results.append((a,fibo(a)))
    print("results : {}".format(results))
    _end = time.time()
    print("SP runtime : {}".format(_end-_start))

    _mstart = time.time()
    work = funcmap(fibo,worklist)
    results = work.run()
    print("results : {}".format(results))
    _mend = time.time()
    print("MP runtime : {}".format(_mend-_mstart))

希望有帮助。在

相关问题 更多 >