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

标签 python python-3.x multithreading amazon-web-services 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()

在我的本地机器上,此代码运行良好。我收到的输出是:
This starts
This should execute
.
.
.
Hello User
('b', 'a')

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

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

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

最佳答案

您是否尝试添加 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()

产生这个输出:
This starts
Hello User
b a
This should execute

关于python - 使用 Python3 在 AWS lambda 中进行多线程处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53386968/

相关文章:

c++ - const 对象的无锁重载和共享

c - 如何按值将结构传递给 pthread?

python - 除运行 py 文件外,无法在 python-eve 中包含模型

python - AttributeError: 'NoneType' 对象没有属性 'pencolor'

python - 如何在没有函数的情况下将 executor.map 应用于 for 循环?

python - 从 HTML 创建数据框

python - 尝试失败,但代码不执行

python - 添加到数据库时时间值略有偏差

python - 如何在 python-socketio 上发送消息

java - 在多线程系统中使用静态 java.sql.Connection 实例是否安全?