简体   繁体   English

NodeJS 集群全局变量

[英]NodeJS cluster global variable

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它完全按照您指定的方式执行操作:_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);
}

This yields这产生

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM