我正在尝试执行以下 AWS lambda:
index.js:
const test = require("test");
exports.handler = async (event) => {
await test.main();
};
测试.js:
const {Worker} = require("worker_threads");
const main = () => {
let num1 = 10;
let num2 = 20;
const worker = new Worker("./worker.js", {workerData: {num1, num2}});
worker.on("message", result => {
console.log(`${num1} + ${num2} is ${result}`);
});
worker.on("error", error => {
console.log(error);
});
worker.on("exit", exitCode => {
console.log(exitCode);
});
console.log("I am here!");
}
exports.main = main;
工人.js:
const {parentPort, workerData} = require("worker_threads");
const getSum = (num1, num2) => {
return num1 + num2;
}
parentPort.postMessage(getSum(workerData.num1, workerData.num2));
当我在笔记本电脑上运行相同的程序时,它运行良好。我一直看到工作线程的输出。
我的笔记本电脑上的输出:
❯ node index.js
I am here!
10 + 20 is 30
0
lambda 上的输出:
START RequestId: c178d74b-da57-4765-9fa7-77d3fc83d645 Version: $LATEST
2021-08-31T14:33:37.353Z c178d74b-da57-4765-9fa7-77d3fc83d645 INFO I am here!
END RequestId: c178d74b-da57-4765-9fa7-77d3fc83d645
REPORT RequestId: c178d74b-da57-4765-9fa7-77d3fc83d645 Duration: 2.12 ms Billed Duration: 3 ms Memory Size: 10240 MB Max Memory Used: 108 MB
当我运行 lambda 时,输出非常随机。有时我会看到工作线程的输出,有时我看不到。
为什么程序在 AWS lambda 和我的笔记本电脑上的执行存在差异?