这是从nodejs api复制的:
我想做的是在master中执行后台作业,并在worker中接受http请求。
如果我注释掉后台工作部分,那么效果很好。
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
const sleep = require('sleep');
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
// background jobs start
while(true) {
console.log(123)
sleep.sleep(1) // do_background_jobs()
}
// background jobs end
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
这是日志:
Master 45476 is running
Worker 45479 started
Worker 45483 started
Worker 45482 started
Worker 45478 started
但netstat
显示8000已关闭。 cource curl
失败。
答案 0 :(得分:1)
你的while循环阻止了&#34; event loop&#34;因此在主要过程中什么都不会发生。你应该将你的while循环转换为这个代码,以防止阻塞IO。
setInterval(() => {
console.log("123")
}, 1000)