我试图在特定群集中执行某个功能,但我在主进程中分配变量时遇到了一些奇怪的问题。
const cluster = require('cluster');
let _checkId = null; // This stores the cluster id
if(cluster.isMaster) {
for(let i = 0; i < 4; i++) {
// Assign _checkId
if(_checkId === null) _checkId = (i + 1);
console.log(_checkId);
cluster.fork();
}
} else {
console.log('Cluster id: ' + cluster.worker.id);
console.log('_checkId ' + _checkId);
console.log(_checkId === cluster.worker.id);
}
这个输出是:
1
1
1
Cluster id: 3
_checkId null // --> This doesn't make sense
false
Cluster id: 1
_checkId null
false
Cluster id: 2
_checkId null
false
基本上我想要实现的是我可以拥有多个集群,但只有一个集群应该执行特定的功能。
答案 0 :(得分:1)
它正在执行您要指定的操作:_checkId等于null,并且仅在主进程上分配
const cluster = require('cluster');
let _checkId = null; // This stores the cluster id
if(cluster.isMaster) {
for(let i = 0; i < 4; i++) {
// Assign _checkId
if(_checkId === null) _checkId = (i + 1);
console.log(_checkId);
cluster.fork();
}
} else {
// _checkId remains null
_checkId = 'foo';
console.log('Cluster id: ' + cluster.worker.id);
console.log('_checkId ' + _checkId);
console.log(_checkId === cluster.worker.id);
}
这会产生
Cluster id: 3
_checkId foo // --> This makes sense
...
Cluster id: 1
_checkId foo
...
Cluster id: 2
_checkId foo
...