【发布时间】:2016-06-23 21:09:52
【问题描述】:
我有一个用 NodeJS 编写的 AWS Lambda,调用过程非常简单
NODEJS -> NodeModule(CPP) -> Extern C Function,这个设置是用 node-gyp 编译的。 你可以在https://drive.google.com/open?id=0B-2d-CuY5fkwS3lwdE96R1V6NEk看到完整的代码
CPP 节点模块调用 C 中的一个函数,该函数运行一个循环。并增加两个变量,一个在 C 函数的范围内,另一个在 C 代码的主范围内。
当您在本地运行此代码时。循环递增,两个变量都达到 11,正如预期的那样,你运行了多少。但是,当您在 AWS Lambda 中运行相同的代码时,每次调用都会有某种“内存”。并且一般范围内没有被重置的变量正在增加,是 11、22、33 等的倍数。
重复一遍,这永远不会在本地发生,两个变量始终为 11。 你可以通过运行构建 1. node-gyp clean 配置构建 2. node app.js(用于本地运行)
Index.js 用于 AWS Lambda
我真的无法解释这种行为? Lambda 是否有某种上下文或某种“内存”或缓存?
我已经为此创建了一个开放 API 网关。 (随时刷新并查看正在运行的“记忆”)。
https://koj2yva6z9.execute-api.us-east-1.amazonaws.com/dev/testLambdaCache
这种行为有时不一致,有时计数会重置。或者您可以通过上传新的 AWS lambda 代码来重置。
感谢您对这种奇怪行为的任何想法。
app.js(用于本地测试)
var addon = require('./build/Release/addon');
console.log(addon.testCache());
console.log(" addon method completed");
index.js(用于 lambda)
console.log('Loading function');
exports.handler = (event, context, callback) => {
var addon = require('./build/Release/addon');
var returnvalue=addon.testCache();
console.log(returnvalue);
console.log(" addon method completed");
callback(null, "success::"+returnvalue);
}
base.cc(C 代码的包装器)
#include <node.h>
#include <iostream>
#include <stdlib.h>
#include<string>
#include<cstring>
using namespace std;
extern "C" char* testCache();
namespace demo {
using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Exception;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
cout << "C++ method started\n";
char *returnStrings=NULL;
returnStrings= testCache();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returnStrings ));
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "testCache", Method);
}
NODE_MODULE(addon, init)
}
decoder.c(运行循环的c代码)
int tmpCounter=0;
char* testCache()
{
int counter=0;
printf("Local counter --> %d Global Counter --> %d\n",counter,tmpCounter);
for(int i=0;i <10; i++)
{
counter = counter +1;
tmpCounter = tmpCounter +1;
//sleep(1);
}
printf("Local counter --> %d Global Counter --> %d\n",counter,tmpCounter);
counter=counter+1;
tmpCounter=tmpCounter+1;
char strCounter[100];
char strTmpCounter[100];
snprintf(strCounter, 16, "%d", counter);
snprintf(strTmpCounter, 16, "%d", tmpCounter);
char *returnString=NULL;
returnString=malloc(1000);
strcat(returnString, "Count:");
strcat(returnString, strCounter);
strcat(returnString, " TmpCount:");
strcat(returnString, strTmpCounter);
strcat(returnString, "\0");
printf("%s\n",returnString);
fflush(stdout);
return returnString;
}
【问题讨论】:
-
发布您的代码。你不能与世界分享你的 gdrive...顺便说一句,我可以猜到:本地范围的 var 是在没有初始化的情况下声明的,我的意思是:
int local_val;所以UB -
文件有多个,除了google drive有没有更好的分享方式?
-
谢谢我也在这里添加了最小代码。
标签: c node.js amazon-web-services aws-lambda