使用 Python3 在 AWS lambda 中进行多线程处理

Sha*_*n26 8 python multithreading amazon-web-services python-3.x aws-lambda

我正在尝试在 AWS lambda 中实现多线程。这是一个示例代码,它定义了我试图在 lambda 中执行的原始代码的格式。

import threading
import time

def this_will_await(arg,arg2):
  print("Hello User")
  print(arg,arg2)

def this_should_start_then_wait():
  print("This starts")
  timer = threading.Timer(3.0, this_will_await,["b","a"])
  timer.start()
  print("This should execute")

this_should_start_then_wait()
Run Code Online (Sandbox Code Playgroud)

在我的本地机器上,此代码运行良好。我收到的输出是:

This starts
This should execute
.
.
.
Hello User
('b', 'a')
Run Code Online (Sandbox Code Playgroud)

那些 3 。表示它等待了 3 秒才完成执行。

现在,当我在 AWS lambda 中执行相同的操作时。我只收到

This starts
This should execute
Run Code Online (Sandbox Code Playgroud)

我认为它没有调用 this_will_await() 函数。

Gab*_*mbe 12

你试过添加timer.join()吗?您需要加入 Timer 线程,否则当父线程完成时,Lambda 环境将终止该线程。

Lambda 函数中的此代码:

import threading
import time

def this_will_await(arg,arg2):
  print("Hello User")
  print(arg,arg2)

def this_should_start_then_wait():
  print("This starts")
  timer = threading.Timer(3.0, this_will_await,["b","a"])
  timer.start()
  timer.join()
  print("This should execute")

this_should_start_then_wait()

def lambda_handler(event, context):
    return this_should_start_then_wait()
Run Code Online (Sandbox Code Playgroud)

产生这个输出:

This starts
Hello User
b a
This should execute
Run Code Online (Sandbox Code Playgroud)