DEV Community

Cover image for Multi Threading In Lambda Function
๐Ÿš€ Vu Dao ๐Ÿš€
๐Ÿš€ Vu Dao ๐Ÿš€

Posted on โ€ข Edited on

3 2

Multi Threading In Lambda Function

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 ๐ŸŒ 

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how theyโ€™re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More