NodeJS 集群全局变量
NodeJS cluster global variable
我正在尝试在特定集群中执行函数,但在我的主进程中分配变量时遇到一些奇怪的问题。
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
基本上我想要实现的是我可以有多个集群,但只有一个集群应该执行特定功能。
它完全按照您指定的方式执行操作:_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
...
我正在尝试在特定集群中执行函数,但在我的主进程中分配变量时遇到一些奇怪的问题。
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
基本上我想要实现的是我可以有多个集群,但只有一个集群应该执行特定功能。
它完全按照您指定的方式执行操作:_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
...