I'm trying to execute a function in a specific cluster, but I'm having some strange issues with assigning variables in my master process.
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);
}
The output for this is:
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
Essentially what I'm trying to achieve is that I can have multiple clusters, but only one cluster should execute a specific function.
It's doing exactly what you're specifying to do: _checkId does equal null, and only is assigned on your master process
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);
}
This yields
Cluster id: 3
_checkId foo // --> This makes sense
...
Cluster id: 1
_checkId foo
...
Cluster id: 2
_checkId foo
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.