如何防止Node.js 12辅助线程立即终止?

Pat*_*und 4 javascript multithreading worker-thread node.js

我有一个运行Express服务器的Node.js应用程序和一个定期执行某些操作的工作线程

当服务器停止时,我需要清理与工作线程启动时打开的外部系统的连接。

我试图在进程上为SIGTERM和SIGINT信号添加一个处理程序,但这没有用,工作线程中的处理程序函数未调用,当父进程接收到SIGINT或SIGTERM时,它会立即以退出代码1退出。父进程也有这些其中的处理程序被调用。

这是重现此问题的简单代码示例:

start.js

const http = require("http");
const express = require("express");
const path = require("path");
const { Worker } = require("worker_threads");

let myWorker = null;

process.on("SIGTERM", stop);
process.on("SIGINT", stop);

const app = express();
const server = http.Server(app);

myWorker = new Worker(path.join(__dirname, "./worker.js"));

myWorker.on("exit", code => console.info(`Worker exited with code ${code}`));

server.listen(3000);

function stop() {
  console.log("Main process: stop()");
  process.exit(0);
}
Run Code Online (Sandbox Code Playgroud)

worker.js

process.on("SIGTERM", stop);
process.on("SIGINT", stop);

setInterval(() => console.log("beep"), 1000);

function stop() {
  console.log("Worker process: stop()");
  process.exit(0);
}
Run Code Online (Sandbox Code Playgroud)

当我启动soWorker.js时,当我使用CTRL + C中断进程时,会在控制台上获得以下输出:

???  node start.js
beep
beep
beep
^CMain process: stop()
Worker exited with code 1
Run Code Online (Sandbox Code Playgroud)

希望发生的是:

???  node start.js
beep
beep
beep
^CMain process: stop()
Worker process: stop()
Worker exited with code 0
Run Code Online (Sandbox Code Playgroud)

我希望stop调用工作线程中的函数,以便可以使用它关闭与外部系统的连接,然后以返回代码0正常退出工作线程进程。

而是,工作线程以代码1退出,这是工作线程停止时的默认值

我的问题:

当主进程终止时,如何在工作线程中执行一些清理代码?

我采用上述方法走上正确的路吗?

小智 5

我主要是在这里吐痰,但是我认为这会让您走上正确的路:

添加到start.js

process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
myWorker.once('exit', stop);

function cleanup() {
  myWorker.postMessage('cleanup');
}
Run Code Online (Sandbox Code Playgroud)

worker.js

const { parentPort } = require('worker_threads');

parentPort.on('message', (value) => {
  if (value === 'cleanup') {
    cleanup();
    //then process.exit(0);
  }
});
Run Code Online (Sandbox Code Playgroud)