0

我正在尝试执行以下 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 和我的笔记本电脑上的执行存在差异?

4

1 回答 1

0

您无需等待工作人员异步操作在test.js文件中完成。尝试添加一个在工人完成时解决的承诺。像这样:

const { Worker } = require("worker_threads");

const main = async () => {
  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);
  });

  console.log("I am here!");

  // Awaiting for the worker to finish here
  return new Promise((resolve) => {
    worker.on("exit", (exitCode) => {
      console.log(exitCode);
      resolve();
    });
  });
};

exports.main = main;

或者,您可以设置context.doNotWaitForEmptyEventLoop = false,但不建议这样做,因为它容易出错且难以调试。

于 2022-02-10T19:51:47.027 回答