DEV Community

loading...
Cover image for Multi Threading In Lambda Function

Multi Threading In Lambda Function

vumdao profile image Vu Dao Updated on ・3 min read

Here's a simple multi-threaded program in lambda function.

What’s In This Document

🚀 Create lambda function using chalice

from chalice import Chalice
import threading
import time
from datetime import datetime


app = Chalice(app_name='multithread-test')
app.debug = True


def run_thread(msg):
    app.log.debug(f"Call {msg} and sleep, timestamp {datetime.now()}")
    time.sleep(5)


@app.lambda_function(name='multithread-test')
def handler(event, context):
    thread_list = list()
    for i in range(0, 5):
        msg = f'thread-{i}'
        thread = threading.Thread(target=run_thread, args=(msg,))
        thread_list.append(thread)
        thread.start()

    for t in thread_list:
        t.join()

    return "Done!"
Enter fullscreen mode Exit fullscreen mode
  • Create AWS chalice new project
⚡ $ chalice new-project multithread-test
Enter fullscreen mode Exit fullscreen mode
  • Deploy function
⚡ $ chalice deploy 
Creating deployment package.
Creating IAM role: multithread-test-dev
Creating lambda function: multithread-test-dev-multithread-test
Resources deployed:
  - Lambda ARN: arn:aws:lambda:ap-northeast-2:1111111111111:function:multithread-test-dev-multithread-test
Enter fullscreen mode Exit fullscreen mode

🚀 Run test

  • Invoke lambda function using aws-cli
⚡ $ aws lambda invoke --function-name multithread-test-dev-multithread-test --region ap-northeast-2 outfile 
{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}
Enter fullscreen mode Exit fullscreen mode

🚀 Check result

Alt Text

Ref: https://github.com/vumdao/multithread-in-lambda

Read More

🌠 Blog · Web · Linkedin · Group · Page · Twitter 🌠

Discussion (0)

Forem Open with the Forem app