我正在尝试在 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/