[英]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
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.