5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS Lambda(Python)でmultiprocessing【Python,Lambda】

Last updated at Posted at 2022-01-28

はじめに

Lambda高速化のためのmultiprocessingを使った並列処理です。パッと使いたいときの自分用テンプレです。

実装

LambdaのPython3.6です。

import json
import boto3
from multiprocessing import Process, Pipe
import time

def worker(conn, num):
    # ここに処理を記述
    # boto3を使う場合
    # session = boto3.Session()
    # s3 = session.client('s3')
    print(num)
    response = f'process: {num}'
    time.sleep(1)
    conn.send(response) # 処理結果
    conn.close()

def lambda_handler(event, context):
    
    results = []
    processes = []
    parent_connections = []
    for i in range(10):
        parent_conn, child_conn = Pipe()
        parent_connections.append(parent_conn)
        process = Process(target=worker,args=(child_conn,i))
        processes.append(process)
    for process in processes:
        process.start()
    for process in processes:
        process.join()
    for parent_connection in parent_connections:
        results.append(parent_connection.recv())

    body = json.dumps({'results': results})
    return {
        'statsCode': 200,
        'body': body
    }

並列処理でboto3をたたく場合はスレッド(プロセス)の中でboto3.Session()からclientやresourceを呼びます(参考)。

参考

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?