繁体   English   中英

使用Python3在AWS Lambda中进行多线程

[英]MultiThreading in AWS lambda using Python3

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM